Skip to content Skip to sidebar Skip to footer

How To Use "this" Keyword Inside A Fetch Api Call Result

I'm using the following fetch API to get an API result. I need to set the result data in the state but the 'this' object is unavailable inside the callback function. How can I upda

Solution 1:

You can use arrow functions

fetch(config.apiUrl + '/api/user', {
  headers: authHeader(),
  method: 'GET',
})
  .then(res => {
    return res.json();
  })
  .then(data => {
    this.setState({ id: data.id });
  });

or you can assign the this keyword to a variable and use that like var that = this;

fetch(config.apiUrl + '/api/user', {
  headers: authHeader(),
  method: 'GET',
})
  .then(function(res) {
    return res.json();
  })
  .then(function(data) {
    that.setState({ id: data.id });
  });

Solution 2:

  • Assign this keyword to a variable that's outside the callback where it is still available. Often var self = this; is used.
  • Use 'self' in the callback where you need it.

Post a Comment for "How To Use "this" Keyword Inside A Fetch Api Call Result"