Clarification regarding state updates #2477
-
Hi, I encountered the issue mentioned in this discussion here: #1394 I have a click event handler, in which I want to update my store, then right after updating the store, take some other followup action depending on the new state. However, the value in the component is not immediately updated, as discussed above.
The recommendation there was to have the action return the value immediately, but the specific example seemed a bit simplistic, in that the value being generated and returned is just a random number. In my case, I need to access the store state. The set function returns void, and I couldn't see a way to refer to state outside of that function, so I had to do something like this:
Is there a better way of doing this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This would be better: export const useCountStore = create((set, get) => ({
count: 0,
increment: (qty) => {
set((state) => ({ count: state.count + qty });
return get().count;
},
})); |
Beta Was this translation helpful? Give feedback.
This would be better: