I have a problem with state in react. I’m create state with base empty value. Then i’m using function which set state value and then take new state value (as i thought) into next function. But my state has old value. When i call console.log inside of my function with state i have new value.
I know that useState is async function, but it’s cant’t help me). For creation state i use hook.
const { formData, setFormData } = useSetFormData({
userSearchRequest: "",
checkedUsers: [],
});
const handlUpdateCheckedUser = (userData, isChecked) => {
if (formData.checkedUsers && formData.checkedUsers.length > 0) {
if (!isChecked) {
setFormData((prevFormData) => ({
...formData,
checkedUsers: prevFormData.checkedUsers.map((item) => {
if (item.id === userData.id) {
return {
...item,
readOnlyAccess: false,
readAndEditAccess: false,
};
}
return item;
}),
}));
const changedRecordIndex = formData.checkedUsers.findIndex((item) => item.id === userData.id)
const updatedUserData = formData.checkedUsers[changedRecordIndex];
isAccessToRecord(updatedUserData);
console.log(updatedUserData);
}
}
};
console.log(formData);
useEffect(() => {}, [formData])
In the function "handlUpdateCheckedUser" i’m update state "checkedUsers" and in the same function i’m throw new state into function "isAccessToRecord" (but there is old state).
Console.log outside shows me ne value. I have no idea how to solve that.
2
Answers
If you want to call
isAccessToRecord
aftersetFormData
is done, you should use an useEffect with a dependancy array on theformData
:change your function to this.