Local storage being reset to default after page refresh

Viewed 186

Hi guys recently i am using reactjs to build add to cart function, because I don't have backend server to store customer cart so I store it at localstorage . When i click add to cart the item is being set into the localstorage , However after refreshing the page, cartItems value being set to default.

enter image description here

export const Store = createContext();

const initialState = {
  cart: {
    cartItems :[]
  },

};

export function StoreProvider(props) {
  const [items, setItems] = useLocalStorage('cartItems', []);
  const [state, dispatch] = useReducer(reducer, initialState);
  
  useEffect(() => {
    setItems(state.cart.cartItems);
  }, [setItems,state.cart.cartItems]);
  
  const value = { state, dispatch };
  return (<Store.Provider value={value}>{props.children}</Store.Provider>);
}

function reducer(state, action) {

  switch (action.type) {
    case 'ADD_TO_CART': {
      const newItem = action.payload;
      const existItem = state.cart.cartItems.find(
        (item) => item.id === newItem.id
      );
      const cartItems = existItem
        ? state.cart.cartItems.map((item) =>
            item.id === existItem.id ? newItem : item
          )
        : [...state.cart.cartItems, newItem];
...

1 Answers

When this element renders after a refresh, your useEffect() will run. The first time the useEffect is run, it is setting the items to the value initially in the state (an empty array). You should be able to solve this problem by skipping the items update on the first render, and this can be accomplished by storing a flag in a ref. Something like:

const firstRun= useRef(true);

useEffect(() => {
  if (!firstRun.current) {
    setItems(state.cart.cartItems);
  }
  firstRun.current = false;
}, [firstRun, setItems, state.cart.cartItems]);
Related