AdamKniec
AdamKniec

Reputation: 1717

React Context old state value in api call

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 :)

Upvotes: 1

Views: 865

Answers (1)

Nathan
Nathan

Reputation: 78449

React doesn't immediately update state when you set a new state-- it queues up the change, and will update before the next render. So your "setUserAnswers" call doesn't mean usetAnswers will be different in your try block.

Instead of using your state in the second call, directly use the value you set your state to be, values.userConsent

Upvotes: 1

Related Questions