reactjstypescriptreact-state

zustand typescript persist how to type store


I've this simple store

interface CartState {
  cart: { [id: string]: CartDto };
  addItem: ({ id, image, name, price }: Omit<CartDto, "quantity">) => void;
  removeItem: (id: string) => void;
  reset: () => void;
}
export const useCart = create<CartState>((set, get) => ({
  cart: {},
  addItem: ({ id, image, name, price }) => {
    set(() => {
      const cart = get().cart;
      if (!cart[id]) {
        cart[id] = {
          id,
          image,
          name,
          price,
          quantity: 0
        };
      }

      cart[id].quantity += 1;

      return { cart };
    });
  },
  removeItem: (id) => {
    set(() => {
      const cart = get().cart;

      if (!cart[id]) {
        return { cart };
      }

      const newQuantity = cart[id].quantity - 1;
      if (newQuantity <= 0) {
        delete cart[id];
      } else {
        cart[id].quantity = newQuantity;
      }

      return { cart };
    });
  },
  reset: () => {
    set(() => {
      return { cart: {} };
    });
  }
}));

and it works very well. Problem is when I try to add persist

export const useCart = create<CartState>(
  persist(
    (set, get) => ({
      cart: {},
      addItem: ({ id, image, name, price }) => {
        set(() => {
          const cart = get().cart;
          if (!cart[id]) {
            cart[id] = {
              id,
              image,
              name,
              price,
              quantity: 0
            };
          }

          cart[id].quantity += 1;

          return { cart };
        });
      },
      removeItem: (id) => {
        set(() => {
          const cart = get().cart;

          if (!cart[id]) {
            return { cart };
          }

          const newQuantity = cart[id].quantity - 1;
          if (newQuantity <= 0) {
            delete cart[id];
          } else {
            cart[id].quantity = newQuantity;
          }

          return { cart };
        });
      },
      reset: () => {
        set(() => {
          return { cart: {} };
        });
      }
    }),
    {
      name: "cart",
      getStorage: () => localStorage
    }
  )
);

I've got this error:

Argument of type '(set: SetState, get: GetState, api: StoreApiWithPersist<{ cart: {}; addItem: ({ id, image, name, price }: Omit<CartDto, "quantity">) => void; removeItem: (id: string) => void; reset: () => void; }>) => { ...; }' is not assignable to parameter of type 'StoreApi | StateCreator<CartState, SetState, GetState, StoreApi>'.
Type '(set: SetState, get: GetState, api: StoreApiWithPersist<{ cart: {}; addItem: ({ id, image, name, price }: Omit<CartDto, "quantity">) => void; removeItem: (id: string) => void; reset: () => void; }>) => { ...; }' is not assignable to type 'StateCreator<CartState, SetState, GetState, StoreApi>'.

I've tried with

export const useCart = create<StoreApiWithPersist<CartState>>

with no luck.

What's the right way, please?


Solution

  • Edit: PhilJay's answer is the best answer. This answer is outdated even though marked as the best.

    I had the same issue. What I did was:

    import create, { GetState, SetState } from 'zustand';
    import { devtools, persist, StoreApiWithPersist } from 'zustand/middleware';
    
    const useAssetStore = create<AssetStoreType, SetState<AssetStoreType>, GetState<AssetStoreType>, StoreApiWithPersist<AssetStoreType>>(
    persist(
        devtools((set) => ({
            logo: '',
        })),
        { name: 'assetStore', version: 1, getStorage: () => localStorage }
    ));
    

    So, in your case, you need to explicitly add:

    create<CartState, SetState<CartState>, GetState<CartState>, StoreApiWithPersist<CartState>>