I'm using Redux toolkit and adding product items to the cart using redux in my eCommerce app, products are adding to the cart perfectly also I tried to store the added products to the localstorage
which is also working fine but the thing is How can I use those items from localstorage
to display the <CartItems>
even after refreshing the page.
Here is my reducer:-
const productItemsSlice = createSlice({
name: "product",
initialState: {
items: [],
totalQuantity: 0,
localStorageItems: [],
},
reducers: {
addProduct(state, action) {
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: 1,
totalPrice: newItem.price,
name: newItem.name,
image: newItem.image,
category: newItem.category,
});
} else {
existingItem.quantity = existingItem.quantity + 1;
existingItem.totalPrice = existingItem.totalPrice + newItem.price;
}
// LOCAL STORAGE
localStorage.setItem("list", JSON.stringify(state.items));
state.localStorageItems = JSON.parse(localStorage.getItem("list"));
},
},
});
And here I'm trying to access those setted cartItems to the localstorage:-
//<CartItems />
//Here state.productItem is from configureStore reducer object:-
// const store = configureStore({
// reducer: {
// productItem: productItemsSlice.reducer,
// }
// })
const productItems = useSelector((state) => state.productItem.localStorageItems);
const items = productItems.map((el) => {
return (
<CartItems
key={el.id}
item={{
id: el.id,
name: el.name,
image: el.image,
price: el.price,
category: el.category,
totalPrice: el.totalPrice,
quantity: el.quantity,
}}
/>
);
});
Please suggest me how can I achieve this, also if I remove items from cart.