1

How can I wait for a dispatch to have updated the state? I didn't find anything in the useReducer API docs, neither do I find any indication in the TypeScript type defininition.

Here is what I have tried but did not work:

await new Promise<void>((resolve) => {
  dispatch({ type: DO_SOMETHING, something });
  resolve();
});

console.log(state.something); // still the old version
user1283776
  • 19,640
  • 49
  • 136
  • 276

2 Answers2

5

How can I wait for a dispatch to have updated the state?

You can't.

In any particular render, state and props of the component do not change, they are constant within that render. Component will have to re-render in order for it to see the new prop and state values.

In your case, you can only access the updated state after the reducer function has updated the state of your component and component has re-rendered.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
-2

The waiting state you need to create by yourself

for example

dispatch(doSomethingAction())

const doSomeThingAction = () => {
   dispatch({type: 'LOADING'})

   // do something 
   .
   .
   .
   .
   // something has done
   dspatch({ type: SUCCESS, something });
}
Monzoor Tamal
  • 790
  • 5
  • 15