How do you debug code that use zustand? #2519
-
|
the technique I use is const myproperty = useStore((state) => state.myproperty);<pre style={{ width: '100%', height: '20vh', overflow: 'auto' }}>
{JSON.stringify(myproperty, null, 4)}
</pre>I tried the extensions zukeeper and zusty, however they make my code throw errors. I don't want to update my code because of an extension. example of throw: I initialize a state property, I get the property directly without getter like it's done with "bear" in the doc of zustand.. it throws that my array is undefined would you have a better technique to know what zustand state is and help with debugging? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
|
@fredericrous would you mind sharing us a minimal repro on stackblitz? |
Beta Was this translation helpful? Give feedback.
-
|
Yes, Redux DevTools extension works great with Zustand via the devtools middleware, and that's what many developers use. But for quick console debugging, you might prefer to expose the store manually. Create a simple and shared utility function in a separated module (for instance debug-utils) export const devZustand = (store: any, name: string) => {
if (process.env.NODE_ENV === 'development') {
window.$store = window.$store || {};
window.$store.getters = window.$store.getters || {};
window.$store.getters[name] = () => store.getState();
window.$store.setters = window.$store.setters || {};
window.$store.setters[name] = (state: any) => store.setState(state);
}
}// Usage in your store file
import { create } from 'zustand';
import { devZustand } from './debug-utils';
const useCounterStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 }))
}));
devZustand(useCounterStore, 'counter');Then in browser console: window.$store.getters.counter() // Returns {count: 0}
window.$store.setters.counter({count: 5}) // Updates state |
Beta Was this translation helpful? Give feedback.
https://github.com/pmndrs/zustand?tab=readme-ov-file#redux-devtools
The easiest way I see is using the built-in
devtoolsmiddleware from zustand. With that you need a Redux Devtools or similar extension and you can see pretty much everything from the extension itself.Or you can use the logger recipe from zustand docs