0

I'm using redux-thunk. I need to make a state empty and then fill it with data. For some reason, I have two separate actions for that, emptyName, addName.

So what I was doing was just to dispatch them in a row, like:

dispatch(emptyName());
dispatch(addName("London"));

but I want to wait for the first one to finish, then send the other one just to make sure that if the first one is messed up for any reason we don't dispatch the second action.

How to do that? I believe dispatch is not a promise so I cannot just do:

await dispatch(emptyName());
dispatch(addName("London"));

(please don't say that it's not necessary to do for this case. Because I may want to do it later in other cases that are more critical and there I may really have to wait for the first on to finish successfully)

P.S. If it's not possible with thunk, I'm open to saga solutions as well :)

Alexander van Oostenrijk
  • 3,691
  • 1
  • 16
  • 32

1 Answers1

0

If you're using redux-thunk, you can just return a Promise from your action and use .then (or await)

emptyName().then(() => {
  addName("London");
});

I've created a contrived example using setTimeout in the actions in place of data fetching, but the principle is the same.

https://codesandbox.io/s/redux-thunk-9gbnj

aoshea
  • 36
  • 3