-
What's the proper way of using the immer middleware in Typescript if we are using createStore to use React Context? Example
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 24 replies
-
Is it only an issue with In general, it would work like something like this: import { createContext, useContext } from 'react'
import { createStore, useStore } from 'zustand'
const store = createStore(...) // vanilla store without hooks
const StoreContext = createContext<typeof store | null>(null)
const App = () => (
<StoreContext.Provider value={store}>
...
</StoreContext.Provider>
) |
Beta Was this translation helpful? Give feedback.
-
@dai-shi I think I may have figure it out. My first instinct was to try to import the
The missing piece was the immer mutator reference (["zustand/immer", never]). I had missed this link Codesandbox working example: https://codesandbox.io/s/little-worker-t306nw?file=/src/store.tsx |
Beta Was this translation helpful? Give feedback.
-
Incase you are nesting multiple middlewares.... import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
type State = {
count: number;
setCount: (newCount: number) => void;
};
// Note that the order you apply the middleware correlates to the order in the type
create<State, [['zustand/devtools', never], ['zustand/immer', never]]>(
devtools(
immer((set) => ({
count: 0,
setCount: (newCount: number) => set((state) => void (state.count = newCount)),
})),
),
); |
Beta Was this translation helpful? Give feedback.
@dai-shi I think I may have figure it out. My first instinct was to try to import the
WithImmer
type but noticed that wasn't available as an export. Here's an example on how I got it to work