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

94
Visualizações
Mutating value in a React state object

I feel really stupid for asking such a simple question like this, but for some reason I forgot how to change the value in a React state object. For example:

const initialState = {
   likes: 100,
   dislikes: 25,
   isLiked: false,
   isDisliked: false
}

const [data, setData] = useState(initialState)

const handleLikes = e => {
    if (data.isLiked) {
        setData({ ...data, likes: data.likes - 1 });
    } else {
        setData({ ...data, likes: data.likes + 1 });
    }

    setData({ ...data, isLiked: !data.isLiked })
}

<button className={`like-button ${data.isLiked ? 'liked' : ''}`} onClick={handleLikes}>Like | <span className='likes-counter'>{data.likes}</span></button>

The confusing part, the part that made me ask this question, is the likes: data.likes + 1 part. When I click the button, it adds/removes the className as intended, but the value never changes. I know this is such a simple thing but I have spent a while on this.

What is wrong with the likes: data.likes + 1?

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

0

The two subsequent setData calls end up "overwriting" each other since the data captured by your handleLikes will not have changed after you call setData.

You'll want to use the functional form of setState to be able to reliably look at the current value (even when asynchronous modifications are in queue, then return a new value based on it:

const handleToggleLikes = (e) => {
  setData((data) =>
    data.isLiked
      ? { ...data, likes: data.likes - 1 }
      : { ...data, likes: data.likes + 1 },
  );
  setData((data) => ({ ...data, isLiked: !data.isLiked }));
};

You can do both of these modifications in one invocation:

const handleToggleLike = e => {
    setData(data => ({
        ...data,
        likes: data.likes + (data.isLiked ? -1 : 1),  // decrease if previously liked
        isLiked: !data.isLiked,
    }));
}
about 4 years ago · Juan Pablo Isaza Relatório

0

There are two ways to use a setState function to update the state object:

  1. Pass it the new state object (which is what you are doing in your code)
  2. Pass it a callback function that takes the current state object as argument, uses it to create the new state object, and returns the new state object.

Whenever you want to use the current state object to create a new state object, you must use the second way. In your case, your code:

setData({...data, likes: data.likes - 1})

uses the current state object (data) to create the new state object. So you must use a callback instead, like this:

setData((cur_data)=>({...cur_data, likes: cur_data.likes-1}))

Note that I am using the arrow syntax in the callback function to return the new state object.

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