Next Js 14
I want to implement storage of products added to the cart using localStorage.
I'm using this approach now:
- Create LocalStorage component, and insert data from localstore to zustand store
- Use on top level in page
"use client";
import { useAddBasket } from "@/shared/hooks";
import { useEffect } from "react";
export const LocalStorage = () => {
const { init } = useAddBasket(); // zustand store
useEffect(() => {
const storage = localStorage.getItem("basket");
if (storage) {
const products = JSON.parse(storage);
init(products);
}
}, []);
return <></>;
};
In this case I avoid mistakes ReferenceError: localStorage is not defined but i think this is the wrong approach.
Another problem is that some data, such as the number of products in the cart, is 0 when updating the page, and becomes correct only after init() function is processed.
How can I improve the experience with localStorage?
Because of the window its not working properly.