Currently, I am attempting to set an initial state (items) to an array of objects or retrieve the same from localStorage. However, I am encountering the following error.
Type 'number' is not assignable to type '{ id: string; price: number; quantity: number; totalPrice: number; name: string; }[]'.ts(2322) cart.ts(4, 3): The expected type comes from property 'items' which is declared here on type 'SliceState'
type SliceState = {
items: {
id: string;
price: number;
quantity: number;
totalPrice: number;
name: string;
}[];
totalQuantity: number;
totalPrice: number;
};
const initialState: SliceState = {
items: [] | localStorage.getItem("cart"),
totalQuantity: 0,
totalPrice: 0,
};
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
addItemToCart(state, action: PayloadAction<any>) {
const newItem = action.payload;
const existingItem = state.items.find((item) => item.id === newItem.id);
state.totalQuantity++;
if (!existingItem) {
state.items.push({
id: newItem.id,
price: newItem.price,
quantity: newItem.quantity,
totalPrice: newItem.price * newItem.quantity,
name: newItem.name,
});
} else {
existingItem.quantity += action.payload.quantity;
existingItem.totalPrice =
existingItem.totalPrice + newItem.price * newItem.quantity;
}
localStorage.setItem("cart", JSON.stringify(state.items));
}
}
Is there a way to achieve what I'm attempting to do? I am also working with Next.js and I am aware that SSR can pose challenges with localStorage.