Majoren Majoren - 1 month ago 10
Javascript Question

ReactJS: How to rerender component after fetching data

So I have a component which displays some data fetched from an external API and saved to localStorage. I have put a fetchData() function that does the job, and I call this function from within componentWillMount(). It looks like this:

componentWillMount() {
this.fetchData();
}

...

fetchData() {
if(localStorage.myData === undefined) {
fetch(apiUrl,{
method: 'GET',
headers: ...
})
.then(function(data) {
localStorage.setItem('myData', data);
}).catch(function(error) {
// error handling
})
} else { return true; }
}


The idea here is to check on every render if the data is set in localStorage, otherwise fetch it, save data and then rerender. However, I can't get it to rerender after the data is stored in localStorage. I have tried using
this.setState({data: data})
instead in the fetchData function, but
this
is undefined.

What am I doing wrong here? Thank's in advance.

Answer

this in your class has a different context than the this inside of your then() function. For your particular case, you can do the following

 fetch(apiUrl,{
    method: 'GET',
    headers: ...
  })
  .then(function(data) {
    // This now refers to your component
    this.setState({data: data});  
  }.bind(this))
   .catch(function(error) {
    // error handling
  })

Or as Utro suggested, you can use arrow functions that will not create its own context thus allowing you to use this appropriately.

 fetch(apiUrl,{
    method: 'GET',
    headers: ...
  })
  .then(data => {
    // This now refers to your component
    this.setState({data: data}); 
  }).catch(function(error) {
    // error handling
  })