TheWebs TheWebs - 5 months ago 87
Javascript Question

Cannot call callback functions on setState in componentDidMount ?? - React

Consider the following simple code:

componentDidMount() {
this._fetchData();
}

_fetchData() {
let url = UrlFormatter() + '/api/v1/blogs/';

$.get(url, (result) => {
if (result.status === 401) {
this.setState({
error: 'Your session has expired. We cannot load data.',
});
} else {
console.log('obvs here');
this.setState({
error: null,
data: result,
}, () => {
console.log('dasddsa');
this._setUpPostCollapseStatus();
});
}
}).fail((response) => {
this.setState({
error: 'Could not fetch blogs, something went wrong.'
});
});
}


If we investigate the console we see:

obvs here


But we never see:
dasddsa
, now either this is a bug, or you cant call a callback function on
setState
in
componentDidMount
- Or I fail at ES6.

Ideas?

lux lux
Answer

Hm, I wasn't able to replicate this; not sure if this'll be helpful, but here's an example of resolving a promise in componentDidMount and using the setState callback:

http://codepen.io/mikechabot/pen/dXWQAr?editors=0011

promise

const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve('Fetched data!')
  }, 2000)
})

component

  componentDidMount() {
    console.log('Mounting...');
    promise
      .then((data) => {
        this.setState({ data }, () => {
          console.log('Data loaded')
        })
      })
      .catch(error => {
        console.log('Error', error);
      })
  }

console

> "Mounting..."
> "Data loaded"