Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 596
user3887366 Avatar asked Sep 12 '25 14:09

user3887366


2 Answers

When using zustand with TypeScript, you should use the curried version of create<T>(...) as stated in the first paragraph of the docs.

Replacing

  export const useCart = create<CartState>( 

by

  export const useCart = create<CartState>()( 

should solve the problem.

like image 68
PhilJay Avatar answered Sep 15 '25 03:09

PhilJay


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>>
like image 39
AvvosMeyz Avatar answered Sep 15 '25 05:09

AvvosMeyz