Separating / merging state using immer middleware + TS
See original GitHub issueI’d ideally want to use zustand with immer and TS and to be able to extract the actions from the values. How would one combine these two patterns? https://github.com/pmndrs/zustand/issues/211#issuecomment-710782706:
import create from 'zustand'
const createActions = (set) => ({
setTitle: (title) => set({ title }),
toggle: () => set(prev => ({ done: !prev.done })),
})
const useStore = create((set) => ({
title: 'foo',
done: false,
...createActions(set),
}))
https://github.com/pmndrs/zustand/pull/169#issuecomment-687770407:
const immer = <T extends State>(
config: StateCreator<T, (fn: (state: T) => void) => void>
): StateCreator<T> => (set, get, api) =>
config((fn) => set(produce(fn) as (state: T) => T), get, api);
const useStore = create<{
bees: boolean;
setBees: (b: boolean) => void;
}>(
immer((set) => ({
bees: false,
setBees: (input) =>
set((state) => {
state.bees = input;
})
}))
);
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
zustand - npm
Start using zustand in your project by running `npm i zustand`. ... The set function merges state. ... Have you tried immer?
Read more >zustand - Bountysource
I'd ideally want to use zustand with immer and TS and to be able to extract the actions from the values. How would...
Read more >How to get better and easier state management with Redux ...
Learn through a simple project what state management improvements Redux Toolkit has to offer and whether it will be ideal for your project....
Read more >How I Setup Redux Toolkit and RTK Query the right way
In this guide, I will show you how to set up Redux Toolkit and RTK Query with React and TypeScript the right way....
Read more >Immer middleware - Zustand Documentation
The Immer middleware enables you to use an immutable state in a more convenient way. Also, with Immer you can simplify handling immutable...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
A follow-up:
https://codesandbox.io/s/zustand-array-tdtph?file=/src/App.tsx
Casting in the producer works, but I kinda feel I’m breaking stuff here:
The inferred type of
set
here is actually:Closing this. For namespacing, track the issue in #178.