Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
React setState() not update the state

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda