vendredi 30 octobre 2020

Using Localstorage with Redux in React

I am working on an ecommerce site in React/Redux. I want to save the user's cart into the localstorage each time after an action has been dispatched in Redux. My code for that looks like this -

import { createSlice } from "@reduxjs/toolkit";

export const cartSlice = createSlice({
  name: "cart",
  initialState: {
    cart: [],
  },
  reducers: {
    addToCart: (state, action) => {
      state.cart = [...state.cart, action.payload];
      localStorage.setItem("Cart", JSON.stringify(state.cart));
    },
    removeFromCart: (state, action) => {
      state.cart = [];
    },
  },
});

export const { addToCart, removeFromCart } = cartSlice.actions;

export const selectCart = (state) => state.cart.cart;

export default cartSlice.reducer;

I did this to solve the problem of the cart getting empty whenever the site refreshes (because I was storing cart in state).

But here, everything works fine until the site refreshes. The products get added to the localstorage.

Now, when I refresh my site, since I am setting localstorage to the state of the cart, each time I refresh, the previous localstorage gets deleted and is overridden by the new state of the cart (because even the state of cart gets changed after refresh).

Is there any other way around it?

I tried by best to explain what I'm facing. Hope it's understandable.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire