I want to be able to store items selected from my home page in Local Storage, as I'm using useStateValue().
The items display on the Checkout page correctly, however, on refreshing, the Checkout page becomes empty and returns to zero. The code below works fine with normal useState. I don't know what I am missing when using useStateValue().
My code:
import React from "react";
import "./Checkout.css";
import CheckoutProduct from "./CheckoutProduct";
import { useStateValue } from "./StateProvider";
import Subtotal from "./Subtotal";
function Checkout() {
const [{ basket, user }, dispatch] = useStateValue();
React.useEffect(() => {
const data = localStorage.getItem("my-cart-list");
if (data) {
dispatch(JSON.parse(data))
}
}, []);
React.useEffect(() => {
localStorage.setItem("my-cart-list", JSON.stringify(basket))
});
You forgot the dependency array, which means that the setItem will be called on every render:
React.useEffect(() => {
localStorage.setItem("my-cart-list", JSON.stringify(basket))
});
If you want to call setItem when "basket" changes, you should use:
React.useEffect(() => {
localStorage.setItem("my-cart-list", JSON.stringify(basket))
}, [basket]);