Marina
Marina

Reputation: 187

Saving array to local storage (reactjs)

I'm trying to save products from shopping cart to local storage, but on page refresh it does not work like it suppose to. When I refresh page, products are in shopping cart, but soon as I add new item, it gets erased. Also, deleting product deletes everything, not the specific one when using local storage. This is what I tried:

in App.tsx set array

const [productList, dispatch] = useReducer((state: any, action: any) => {
    switch (action.type) {
      case "ADD_ITEM":
        const noDoubleItems = state.filter((item: any) => item.id !== action.payload.id);
        localStorage.setItem("cart",JSON.stringify([...noDoubleItems, action.payload]));
        return [...noDoubleItems, action.payload];

      case "DELETE_ITEM":
        localStorage.setItem("cart", JSON.stringify(state));
        return state.filter((item: any) => item.id !== action.payload.id);

      default:
        return state;
    }
  }, []);

in Cart.tsx get array

  const storageCart = localStorage.getItem("cart");
  const storageCartObject = storageCart && JSON.parse(storageCart);

Here is code sandbox: https://codesandbox.io/s/flamboyant-torvalds-tevby?file=/src/components/pages/Cart.tsx:298-1026

Upvotes: 1

Views: 1151

Answers (1)

monsty
monsty

Reputation: 623

Your storageCart is initialized with the localStorage, but your Redux state is not initialized. So, the storageCart is still there, but when you dispatch the ADD_ITEM action, the Store is empty, that's why the first product you added disappears.

You can also use redux-persist to persist the Redux store every time the user refresh the page. So you don't need to handle all the local storage stuff.

Upvotes: 1

Related Questions