How to work correctly with localstorage in Next Js 14?

52 Views Asked by At

Next Js 14

I want to implement storage of products added to the cart using localStorage.

I'm using this approach now:

  1. Create LocalStorage component, and insert data from localstore to zustand store
  2. 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?

1

There are 1 best solutions below

1
Emre On

Because of the window its not working properly.

useEffect(() => {
  if (typeof window !== "undefined") {
    const storage = localStorage.getItem("basket");
    if (storage) {
      const products = JSON.parse(storage);
      init(products);
    }
  }
}, []);