Skip to content
Advertisement

How to set a redux toolkit initial state to an array of object or localstorage with typescript?

i’m currently trying to set an initialState (items) to an array of object or the same thing from the localStorage. The problem is, that i’m receiving this kind of 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 any way to achieve what i’m trying to do ? I’m also using nextjs, i know ssr can be a problem with localstorage.

Advertisement

Answer

You are using incorrect syntax here:

items: [] | localStorage.getItem("cart")

What you meant is:

items: localStorage.getItem("cart") || []
Advertisement