1

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

2
  • Are you using Redux ? Commented May 5, 2020 at 21:18
  • Reducer functions (in redux or other plain react) should really be pure functions, meaning they return a new state and have no other side effects. Writing to local storage is a side effect. Commented May 5, 2020 at 21:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I had to install npm install use-persisted-reducer --save, create persisted reducer like so const usePersistedReducer = createPersistedReducer('state') and replace useReduer with usePersistedReducer, that simple!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.