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

127
Vistas
React - State not updating properly

When the user clicks the Upvote button, the render increments the value however it does not update the data state.

Although, if the user clicks upvote twice (eg: 50, 51, 52), it then saves the value as 51.

const [data, setData] = useState(props);
const [update] = useUpdateSnippet();

// TODO: Implement upvote functionality
const onClick = useCallback(() => {
    setData(previousData => {
      return { 
        ...previousData, 
        votes: data.votes+1
      }
    });
    console.log(data);
    update({
      snippetId: data.id,
      body: data,
      onUpdated: () => {}
    });
  }, 
  [update, data]
)
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The setState has an additional argument where you can pass a callback function, which is guaranteed to run right after state has been updated. Something like this - setState(updater, callback).

From the official doc:

a setState callback (setState(updater, callback)), ... which are guaranteed to fire after the update has been applied.

Here is my snippet which you might apply:


setData({ 
    ...previousData, 
    votes: data.votes+1
  },
  () => {
    console.log(data);
    // your update function call
    update();
  });
    
about 4 years ago · Juan Pablo Isaza Denunciar

0

State update doesn't happen synchronously so update would not get the updated data state.

Store the updated data in a variable and pass that to setData as well as update.

const [data, setData] = useState(props);
const [update] = useUpdateSnippet();

// TODO: Implement upvote functionality
const onClick = useCallback(() => {
  const newData = { ...data, votes: data.votes + 1 };
  setData(newData);
  console.log(data);
  update({ snippetId: newData.id, body: newData, onUpdated: () => {} });
}, [update, data]);
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