not loosing state when user updates the state while an async method concurrently updates the state #2715
Unanswered
melutovich
asked this question in
Q&A
Replies: 1 comment 1 reply
-
@dai-shi Any thoughts on this? |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I would like to know if zustand handles the below automatically and/or what configuration or adjustments might be needed for my intentions to be successful.
I have a custom provider ABCContextProvider that runs an async server request ABC from another party.
There is a useHook from ABC giving the request status 'loading', 'ready', etc.
While the request ABC is loading, I want to store the user's choices in an array. When this ABC request is ready, the choices will be acted upon.
I'm planning for my zustand store to have a state like
type ABCStore = {
isABCReady: boolean
setABCReady: () => void
unprocessedChoices: string[]
actOnChoice: (choice: string) => void
}
The store is created by our nextjs App (created by createStore from zustand vanilla and stored in a useState of the App) and passed in as a prop on the ABCContextProvider. (There are reasons for this that prefer to not go into)
I am using an useEffect hook like
useEffect(() => {
if (abcStatus === 'ready' && !store.getState().isABCReady) {
store.getState()._setABCReady()
}
},[status, store])
I was planning that actOnChoice would store the choices in unprocessedChoices when isABCReady === false
and act on the choice otherwise
setABCReady would loop over the unprocessedChoices and act on the choices and set the state to unprocessedChoices as an empty array and isABCReady is true.
I am concerned what will happen if the user clicks and causes a call to addOnChoice (if that is possible??) while the setABCReady function is being processed as then the later choice might get overwritten when the state is updated by setABCReady when it sets unprocessedChoices to an empty array.
Beta Was this translation helpful? Give feedback.
All reactions