Home > Blockchain >  React setState() not update the state
React setState() not update the state

Time:10-03

State

state = {
    likedPosts: [{movie: '5b21ca3eeb7f6fbccd471816', down: true}],
  };

function

  handleLike(movieId) {
    if (this.state.likedPosts.filter((e) => e.movie === movieId).length > 0) {
      const likedPosts = this.state.likedPosts.filter(function (l) {
        if (l.movie !== movieId) {
          return l;
        }
      });
      console.log(likedPosts); // this returns the expected object
      this.setState({ likedPosts }); // this not work
    } else {
      this.state.likedPosts.push({ movie: movieId, down: true }); // this works
    }
    console.log("now", this.state.likedPosts);
  }

I want push new object if object not in this.state.likedPosts array or remove the object if that object in array.

When object exist in this.state.likedPosts, console.log(likedPosts) returns the expected new array. But this.setState({ likedPosts }) does not update the state. What is the problem in here?

CodePudding user response:

I tried function adding console.log("now", this.state.likedPosts); line to check the state after updating at same time. That is why this problem arises.

  handleLike(movieId) {
    if (this.state.likedPosts.filter((e) => e.movie === movieId).length > 0) {
      const likedPosts = this.state.likedPosts.filter(function (l) {
        if (l.movie !== movieId) {
          return l;
        }
      });
      console.log(likedPosts); // this returns the expected object
      this.setState({ likedPosts }); // this not work
    } else {
      this.state.likedPosts.push({ movie: movieId, down: true }); // this works
    }
    console.log("now", this.state.likedPosts);
  }

Although the state was updated until the function was completed, the old state appeared to be there.

When this is done, the state is not updated in the same function, but when the state is compared using another function at same time, it seems to be working correctly.

CodePudding user response:

You should never modify/mutate state directly (this.state.something = something). You should always use setState method.

To do something after setState you should use second argument of setState.

this.setState({
    likedPosts
}, () => {
    console.log(likedPosts)
});

Also, I would recommend you to start using react hooks.

  • Related