zustdnd functional updates that give you access to the previous state like react's useState
import { create } from "zustand";
interface OneBear {
age: number;
type: "black" | "brown" | "black";
}
interface BearState {
bears: OneBear[];
// just takes in the new value
setBear: (value: OneBear) => void;
// takes in a function that will give you access to the previous state
setBearFunctionally: (value: (prev: OneBear[]) => OneBear) => void;
// takes in a function that will give you access to the previous state or just a plaain value
setBearvalueOrFunctionally: (value: (prev: OneBear[]) => OneBear | OneBear) => void;
}
const useBearStore = create<BearState>()((set) => ({
bears: [],
setBear: (value) => set((state) => ({ bears: [...state.bears, value] })),
setBearFunctionally: (value) => {
set((state) => {
return { bears: [...state.bears, value(state.bears)] };
});
},
setBearvalueOrFunctionally: (value) => {
set((state) => {
return { bears: [...state.bears, typeof value === "function" ? value(state.bears) : value] };
});
},
}));