2

I am running a function that has an API call that brings back a response that I use to set the state and then triggers another function which uses the state that has just been updated. the problem the second function is running before response comes back and updated the state

I have tried .then I thought that should work

import React from "react";
import API from "../../utils/API"
class Content extends React.Component {
    state={
        postID:"",
        statusPost:""
    }

    submitPost = () => {
        API.savePost({
            content: this.state.statusPost,
            post_by: this.props.userInfo.firstname + this.props.userInfo.lastname
        })
        .then(console.log(this.submitPost))
        .then(res => {

            this.setState({ postID:res.data._id })

            console.log(this.state)
        })
            .then(this.addPostID())
            .catch(err => console.log(err));

    }


    addPostID = () => {

    API.postID({
        _id:  this.props.userInfo.user_ID,
        post:this.state.postID
      })

      .then(res => console.log(res))
      .catch(err => console.log(err));

    }
}
blaz
  • 3,981
  • 22
  • 37

1 Answers1

1

The problem here is that setState is asynchronious by itself. It better used for rendering React component based on state changes but not to transfer data between functions calls. So it better to refactor you code this way

submitPost = () => {
    API.savePost({
        content: this.state.statusPost,
        post_by: this.props.userInfo.firstname + this.props.userInfo.lastname
    })
    .then(console.log(this.submitPost))
    .then(res => {

        this.setState({ postID:res.data._id })

        console.log(this.state)
        this.addPostID(res.data._id); // As state will not be updated on this point
    })
        .catch(err => console.log(err));
}

addPostID = (postID) => {

API.postID({
    _id:  this.props.userInfo.user_ID,
    post:postID // Use argument and not state here
  })

  .then(res => console.log(res))
  .catch(err => console.log(err));

}

Alternative approach to this problem can be to use second argument of setState function which is callback that will be called after state update.

For example

this.setState({ postID:res.data._id }, () => this.addPostID()); // Now addPostId will be called after state updated
Fyodor Yemelyanenko
  • 11,264
  • 1
  • 30
  • 38