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?