Home > Back-end >  React Redux - localStorage cart empty after refresh
React Redux - localStorage cart empty after refresh

Time:06-25

After every refresh my cart gets empty. How can i make it persist a refresh and just empty after browser restart?

I added fully code getItem for the initialState. But i don't know how to check for the initialState and if there is no initialstate use setItem...

const savedCartItems = JSON.parse(localStorage.getItem('cartItems')) || [];

const initialState = {
  cartItems: savedCartItems || [], // Cart initially contains no items unless retrieved in localStorage
};

export const addToCart =
  (dish, quantity, variant, toppings, removeIng, sumOfToppings) =>
  (dispatch, getState) => {
    var cartItem = {
      name: dish.name,
      _id: dish._id,
      image: dish.image,
      variant: variant,
      quantity: Number(quantity),
      toppings: toppings,
      removeIng: removeIng,
      prices: dish.prices,
      sumOfToppings: sumOfToppings,
      price: (parseFloat(variant)   sumOfToppings) * quantity,
    };
    if (cartItem.quantity > 20) {
      alert('Du kannst dieses Gericht maximal 20 mal hinzufügen.');
    } else {
      if (cartItem.quantity < 1) {
        dispatch({
          type: 'DELETE_FROM_CART',
          payload: dish,
        });
      } else {
        dispatch({
          type: 'ADD_TO_CART',
          payload: cartItem,
        });
      }
    }

    const cartItems = getState().cartReducer.cartItems;
    localStorage.setItem('cartItems', JSON.stringify(cartItems));
  };

export const deleteFromCart = (dish) => (dispatch, getState) => {
  dispatch({
    type: 'DELETE_FROM_CART',
    payload: dish,
  });
  const cartItems = getState().cartReducer.cartItems;
  localStorage.setItem('cartItems', JSON.stringify(cartItems));
};

CodePudding user response:

As pointed out by mherzig you are persisting your state through your browser's localStorage but you are not getting that data back (at least not correctly).

If you want the quick answer:

  1. Pull your persisted cartItems from localStorage:

const savedCartItems = JSON.parse(localStorage.getItem("cartItems")) || []

  1. Use that value in your initial Redux's state:
const initialState = {
  // Whatever state you might have
  //....

  cartItems: savedCartItems || [], // Cart initially contains no items unless retrieved in localStorage
}

To be sure that your state is correctly persisted, open your brower's devtools and head over to Application then Local Storage, if your data is there then you are sure that your state is persisted.

In case it would help — here's an example I had worked on with Redux Toolkit

CodePudding user response:

Adding this to my store made it work. Thanks to everyone who helped me!

const cartItems = localStorage.getItem('cartItems')
  ? JSON.parse(localStorage.getItem('cartItems'))
  : [];

const initialState = {
  cartReducer: {
    cartItems: cartItems,
  },
};

  • Related