0

I am confused about the order of lifecycle stages in my React app. I have the following class:

constructor(props) {
  super(props);

  this.state = {
    skip: 0
  }

}

fetchMoreArticles() {
  this.props.dispatch(fetchArticles(this.state.skip))
  this.setState({skip: (this.state.skip + 5)})
  console.log(this.state.skip); //This outputs 0 on page refresh???
}

componentDidMount() {
  this.fetchMoreArticles()
}

When I write to the console (see fetchMoreArticles()) I would expect the output to be 5 but it's 0. Could someone explain why?

Note: fetchArticles() is an ajax call using Redux

tommyd456
  • 10,443
  • 26
  • 89
  • 163

1 Answers1

2

setState is asynchronous. So you have to use a callback :

this.setState({skip: (this.state.skip + 5)}, () => {
    console.log(this.state.skip);
})
Valentin Duboscq
  • 970
  • 8
  • 20