Wait for dispatch to end in redux

Viewed 152

I'm using React Native to build an offline app, and, because I need to pass many data between screens, I decided to use redux. However, I have a doubt concerning the dispatch method. The dispatch method is synchronous right? So what happens when I have code after that dispatch, which depends on the changes that the dispatch made? For example, I have this function:

make_action(){ 
 this.props.dispatch(action());
 //rest of the code

}

How can I make sure that the "rest of the code" only runs after the dispatch is completed? Thank you all!!

1 Answers

The short answer is if you want to follow Redux, don't actually put that logic there, where you are indicating with the "rest of the code" comment.

Instead you would use a reducer to handle the result of the action and translate it into a (store) state change. Then you would use the state to drive the impacted view (e.g. container or component), which may be as simple as using that state in its existing render method (if class) or function body (if pure function). Think about the code you are labeling as "rest of the code" and whether it should live in the action itself, state processing (reducer), or the rendered view(s). Typically in a React+Redux app such code as you are proposing would live in one or more of those places, or perhaps it isn't needed at all.

If instead you introduce code where you have the "rest of the code" comment that actually depends on the action having being completed at that point, you are effectively working around (or against) Redux.

Remember that with Redux actions should only return results that are interpreted by reducers to mutate state, which drives views. It's intended to be a unidirectional, cyclical flow of data:

view dispatches action ->

action does something to produce result ->

result is reduced to mutated state, driving updated view ->

... (now we're back to view; repeat)

Related