Created
October 13, 2022 19:00
-
-
Save aphilas/e3e159f8a223706291658081c6f3177f to your computer and use it in GitHub Desktop.
Zustand with immer and persist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import create, { StateCreator } from "zustand" | |
import { persist } from "zustand/middleware" | |
import { immer } from "zustand/middleware/immer" | |
// Custom persist storage | |
import { zustandStorage } from "@app/services/zustand" | |
export interface Entry { | |
sourceId: string | |
quantity: number | |
unitPrice: number | |
} | |
export interface Store { | |
cart: Record<string, Entry> | |
// ... | |
} | |
const ZST_CART_KEY = "zst-cart" | |
const initializer: StateCreator< | |
Store, | |
[["zustand/persist", unknown], ["zustand/immer", never]], | |
[], | |
Store | |
> = (set, get) => ({ | |
cart: {}, | |
// ... | |
}) | |
export const createCartStore = persist(immer(initializer), { | |
name: ZST_CART_KEY, | |
// Or AsynStorage for React Native | |
getStorage: () => zustandStorage, | |
}) | |
export const useCartStore = create<Store>()(createCartStore) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment