Syncronous state updates using Context API + UseReducer

I'm building a react native app with react navigation, which means I can't pass down props to my components the usual way (they are all nested inside a <Stack.Screen> component from react navigation).

Instead, I'm using the react Context API to pass data down through my component tree.

My problem is that everytime I use dispatch, it seems to act asynchronously. If I do:

const Submit = function () {
        //this line is caught by my reducer and the signUpData is added to the state
        dispatch({ type: "signUp", signUpData}) 
        axios({ url:'myapiURL', data: state.signUpData, method: "POST" })

My post request will be sent with undefined instead of the proper signUpData. Whatever I try to do immediately after a dispatch, it is as if the state has not been updated yet, because dispatch is async.

The problem is that dispatch is not supposed to be async (as far as i understand ? the docs are unclear) and because it doesn't return a promise, I can't use .then() or await/async to make sure the dispatch is complete before my axios or console log happens on the next line.

Read more here:

Content Attribution

This content was originally published by Aeltham at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: