Why won't my changes to state show in my componentDidMount lifecycle?

52 views Asked by At

I am building an app using React and for my homepage, I set state in the componentDidMount lifecycle:

export default class HomePage extends Component {
  state = {
    posts: [],
    token: '',
  };

  //Display posts when homepage renders
  componentDidMount() {
    //If token exists, run lifecycle event
    if (this.props.location.state.token) {
      this.setState({ token: this.props.location.state.token });
    }
    Axios.get('http://localhost:3000/api/posts/all')
      .then((req) => {
        this.setState({ posts: req.data });
      })
      .catch((err) => {
        console.log(err.message);
        throw err;
      });
    console.log(this.state);
  }

However when I run the console log at the end of the lifecycle method, it shows posts and token as still being empty. I know they are being populated because the posts from the req.data show up in my JSX. Why does it show state being empty when I console log inside the method?

1

There are 1 answers

0
Tim Bogdanov On BEST ANSWER

React setState is asynchronous!

  • React does not guarantee that the state changes are applied immediately.
  • setState() does not always immediately update the component.
  • Think of setState() as a request rather than an immediate command to update the component.
this.setState((previousState, currentProps) => {
    return { ...previousState, foo: currentProps.bar };
});