IE, Since set(() => ({bears: {a: 0})) is shallowly merged, it would override other parts of {bears} so you would need set((state) => ({bears: {...state.bears, a: 0}}))
Immer makes it `set((state) => state.bears.a = 0)
store/userSlice.ts
import { StateCreator } from 'zustand';
import { User } from '@/API';
import type { AllSlices } from './index';
export interface UserSlice {
user: User;
setUser: (user: User) => void;
}
export const createUserSlice: StateCreator<AllSlices, [['zustand/immer', never]], [], UserSlice> = (
set
) => ({
user: null,
setUser: (user: User) =>
set((state) => {
state.user = user;
}),
});
store/index.ts
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { createUserSlice, UserSlice } from './userSlice';
//To add type & UserSlice with the newSlice
export type AllSlices = UserSlice;
export const useAppStore = create<AllSlices>()(
immer((...args) => ({
...createUserSlice(...args),
}))
);