Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!