If I use actions as a key in store it is stripped out from it for subsequent renders
#3398
Replies: 3 comments
|
@alex-bondarev-linnovate would you mind creating a demo on stackblitz? |
|
The If you're using the The other possibility is a naming collision. zustand internally uses certain keys, and If devtools is the culprit, wrapping the devtools middleware so it excludes the |
|
This usually happens because the So the flow is roughly: {
bears: 0,
actions: { addBear: fn, reset: fn }
}becomes a DevTools snapshot like: { bears: 0, actions: {} }and when that snapshot is applied back, your real A safer pattern is to keep actions at the top level instead of inside a nested object: const useBearStore = create<{
bears: number
addBear: () => void
reset: () => void
}>()(
devtools((set) => ({
bears: 0,
addBear: () => set((s) => ({ bears: s.bears + 1 })),
reset: () => set({ bears: 0 }),
}))
)Then consume only the action you need: const addBear = useBearStore((s) => s.addBear)If you really want the grouped |
Uh oh!
There was an error while loading. Please reload this page.
A bit weird but if I follow TkDodo's advice on separating actions from state and create a hook for it, much like in the example
export const useBearActions = () => useBearStore((state) => state.actions);it fails on subsequent rerenders. So it works fine on initial render but then errors. All other 'dedicated' hooks for the same store work fine even in the same component. I've tripple-checked the syntax.
What is even weirder is that if I change
actionsto something else it works just fine. Has anybody experienced anything like it? I'm pretty sure that the issue is with me and how I do stuff, but still 😃 I've never experienced receiving half of the store in a component simply because I chose the wrong key inside of it (so it seems). I'm receiving everything but the 'actions' bit.All reactions