const [isValid, setisValid] = useState(false);
const GetData = () => {
debugger;
if (type.isValid === "true") {
setisValid (true);
}
else {
setisValid(false);
}
GetMyData(ID, isValid)
.then((response) => {
if (componentMounted.current) {
const apiResult: ApiResult<ItemApproval> = response.data;
if (!apiResult?.success && apiResult?.message) {
onError("Checking validity", apiResult?.message ?? "Error retrieving state value");
}
setData(apiResult.data);
}
})
.catch(function (error: any) {
console.log("Error in GetData: ", error);
if (componentMounted.current) {
onError("Error", "Error retrieving state");
}
});
};
I have the above code, when i debug and inspect variables, isValid is true and setisValid (true);
is being executed but isValid is false on line GetMyData(ID, isValid)
, why isn’t my updated value being piacked?
2
Answers
To address this issue, you can use the updated state value inside the
GetMyData
call by passing the callback version ofsetisValid
. Here’s how you can modify your code to make it work as intended:Not sure why you need to have a state here while you can pass
type.isValid === "true"
this at the place of isValid.one other thing you are facing the issue is because thats how react’s state setter functions work. These works like a Async functions so when you try to run this function your
GetMyData
function completes its execution while yoursetIsValid
is still in the execution phase.To over come this use
GetData
function to only set the state. And have auseEffect
in place with a dependency array of[isValid]
and place yourGetMyData
function in there.