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

135
Vistas
Query call is using old state

I have a submit button and on click I want to update the status to "NEW" and make the query call with this "NEW" status. However, in my current code the query is still using the "OLD" status. Is there a way to make the query call to use the updated "NEW" state? The query doesn't fail however, it uses the "OLD" state

import React,{useState} from "react";
import { gql, useMutation } from '@apollo/client';
import Button                   from "@material-ui/core/Button";

const UPDATE_DATA = gql`
mutation updateData( $data: UpdateDataInput!){
    updateData payload: $data)
  }`

export default function StatusPage() {

 const [updateData] = useMutation(UPDATE_DATA);
 const [status,setStatus] = useState("OLD");
  const handleSubmit = async () => {
    setStatus("NEW")
    try {
      const result = await updateData({
        variables: {
          data: {
            status:status
          }
        }
      });
      if(result.data) {
        console.log("SUCCESS")
      }
    } catch (e) {
      console.log("ERROR")
    }
  };
  return (
      <Button type ="submit" onClick={handleSubmit()}> Submit </Button>
  );
}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Because of useState hook is asynchronous. You can use the useEffect hook and add our state in the dependence array, and you will always get the updated value. Sample:

import { useState, useEffect } from "react";

export default function CountWithEffect() {
    const [count, setCount] = useState(0);
    const [doubleCount, setDoubleCount] = useState(count * 2);
    const handleCount = () => {
        setCount(count + 1);
    };

    useEffect(() => {
        setDoubleCount(count * 2); // This will always use latest value of count
    }, [count]);

    return (
        <div>
            <h2>Count with useEffect</h2>
            <h3>Count: {count}</h3>
            <h3>Count * 2: {doubleCount}</h3>
            <button onClick={handleCount}>Count++</button>
        </div>
    );
}
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