Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 487
Majoren Avatar asked Apr 01 '26 21:04

Majoren


2 Answers

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 their 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
  })
like image 65
John F. Avatar answered Apr 04 '26 10:04

John F.


This object inside .then will refer to object of Promise call not the object of Component.

vat that = this;

declare some variable of this to that and then you can use

that.setState({})
like image 28
Akash Bhandwalkar Avatar answered Apr 04 '26 11:04

Akash Bhandwalkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!