You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Async actions can be pure async/promise functions:
async getStuff(state) {
let res = await fetch('/foo.json')
return { stuff: await res.json() }
},
I don't fully understand how you can really support async actions like in this example.
If getStuff() is called twice before the first call resolves, and the two fetch() operations happen to finish in reverse order (because HTTP servers are unpredictable) doesn't this cause a race condition?
Won't you end up with the stuff from the first request instead of the second?
I understand (from reading this issue) that the internal call to setState() is defferred until the promise resolves - but I don't think that's enough to guarantee that setState() calls are performed in the same order the actions were invoked?
For something like an auto-complete input fetching results from the server-side, it seems like there's a good chance of this actually happening.
Do I have to manually prevent races?
The text was updated successfully, but these errors were encountered:
This is a footgun, yes. In general, concurrent execution of actions that write to the same state properties is a bad idea, unless a locking mechanism is used:
actions=store=>({asyncgetStuff(state){// async actions already typically do an initial store update to indicate pending state.// the suggestion is to also write a lock of some kind here:constlock={};store.setState({pending: true, lock });constres=awaitfetch('/foo.json')conststuff=awaitres.json();// if someone else overwrote our lock, discard the action's return value.if(store.getState().lock!==lock)return;return{pending: false, stuff };}})
I'm wondering about this example in the README:
I don't fully understand how you can really support async actions like in this example.
If
getStuff()
is called twice before the first call resolves, and the twofetch()
operations happen to finish in reverse order (because HTTP servers are unpredictable) doesn't this cause a race condition?Won't you end up with the
stuff
from the first request instead of the second?I understand (from reading this issue) that the internal call to
setState()
is defferred until the promise resolves - but I don't think that's enough to guarantee thatsetState()
calls are performed in the same order the actions were invoked?For something like an auto-complete input fetching results from the server-side, it seems like there's a good chance of this actually happening.
Do I have to manually prevent races?
The text was updated successfully, but these errors were encountered: