I have a component which represents a page. This page has a form. Submitting that form sets the new state in context and uses this new state in the api call. The problem is that old value of the state is visible in api call.
Code structure looks something like this
export const Component = () => {
const { userAnswers, setUserAnswers } = myCustomHook(); // hook based on context
const { saveAnswersOnBackend } = useSaveAnswers()
const handleFormSubmit = async () => {
setUserAnswers(prev => ({
...prev,
userConsent: values.userConsent, // "values" comes from Formik
}))
try {
await saveAnswersOnBackend({ // api call.
userAnswers: {
userConsent: userAnswers.userConsent, // old userConsent value is sent all the time
},
})
} catch (err) {
handleError(err)
}
}
}
Thanks in advance :)