I'm developing a cart system and the problem is that, when I add a product to the cart, it works in context and localStorage; but, when I refresh, the data is gone.
export const DataContext = createContext();
export const DataProvider = ({ children }) => {
const [cart, setCart] = useState([]);
const [state, dispatch] = useReducer(AppReducer, cart);
useEffect(() => {
const cartData = JSON.parse(localStorage.getItem("cart"));
if (cartData) {
setCart(cartData);
}
}, []);
useEffect(() => {
localStorage.setItem("cart", JSON.stringify(cart));
// Cookies.set("cart", cart, { expires: 1 / 24 });
// let products = Cookies.get("cart");
// console.log(products);
}, [cart]);
const addToCart = (newProduct) => {
setCart((prev) => [...prev, newProduct]);
};
return (
<DataContext.Provider value={{ cart, setCart, addToCart }}>
{children}
</DataContext.Provider>
);
};
Then I just import addToCart
function in my product detail page and give the product as parameter.
Dealing with this in Next.JS is so much worse than normal React. I'll be glad to know what I'm doing wrong.
Your localstorage has been writen when you reload the page. Try the following way to prevent set item in localstorage when init.
const initialState = [];
const [cart, setCart] = useState(initialState);
useEffect(() => {
const cartData = JSON.parse(localStorage.getItem("cart"));
if (cartData) {
setCart(cartData);
}
}, []);
useEffect(() => {
if (cart !== initialState) {
localStorage.setItem("cart", JSON.stringify(cart));
}
}, [cart]);