0
votes

I have this cartSlice that I want to persist the cart by using the cookies as an initialState, But the problem is if I call the useSelector to my component the return value are an empty object. The cookies are there but I don't know why it's not being used. The return value of useSelector is an empty object.

cart

[
    {
        "cartItem": {
            "id": "628a1738fd8299ae6659d994",
            "category": "chair",
            "name": "chair",
            "image": "https://res.cloudinary.com/dpxoclpym/image/upload/v1658125036/product-images/chair/chair-beige_02_at0trj.png",
            "color": "beige",
        },
        "itemQuantity": 1,
        "quantity": 1
    },
    {
        "cartItem": {
            "id": "628a1738fd8299ae6659d994",
            "category": "chair",
            "name": "chair",
            "image": "https://res.cloudinary.com/dpxoclpym/image/upload/v1658141184/product-images/chair/chair-navy_02_rrpazi.png",
            "color": "navy",

        },
        "itemQuantity": 1,
        "quantity": 1
    }
]

cartSlice

import { createSlice } from '@reduxjs/toolkit';
import Cookies from 'js-cookie';

const cartItem = Cookies.get('cartItems')
  ? JSON.parse(Cookies.get('cartItems'))
  : [];

const cartSlice = createSlice({
  name: 'cart',
  initialState: {
    cart: cartItem,
    quantity: 1,
    total: 0,
    noRepeatedItem: 1,
  },
  reducers: {
    addToCart: (state, action) => {
      if (action.payload.itemQuantity > 1) {
        state.quantity = action.payload.itemQuantity;
        state.cart.push({
          cartItem: action.payload.cartItem,
          quantity: action.payload.itemQuantity,
        });
      } else {
        state.quantity += 1;
        state.cart.push(action.payload);
      }
    },
  },
});

export const {
  addToCart,
} = cartSlice.actions;