Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda