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>
);
}
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>
);
}