Search code examples
javascriptreactjsreact-hookslocal-storageglobal-state

How I put a global state array of objects inside local storage?


I am working on an ecommerce website. I create a global state using the library in the react-hooks-global-state (the link below). I want the array to save when I refresh or redirect the page. However, when I store it in local storage I get an infinite loop.

library: https://github.com/dai-shi/react-hooks-global-state

____

I tried this method with use effect, now putting the array in local storage works, but getting it out causes the infinite loop:

state:

import { createGlobalState } from "react-hooks-global-state";

const { setGlobalState, useGlobalState } = createGlobalState({
  cartItems: [],
});
export { useGlobalState, setGlobalState };

code:


const [cartItemslit] = useGlobalState("cartItems");

useEffect(() => {
    const data = window.localStorage.getItem("literalcartting");
    if (data !== null) {
      setGlobalState("cartItems", JSON.parse(data));
    }
  });
  useEffect(() => {
    window.localStorage.setItem(
      "literalcartting",
      JSON.stringify(cartItemslit)
    );
  }, cartItemslit);

Solution

  • Your code have the problem of infinite rendering, there is no dependency array in both of the useEffect hooks,

    Try this code,

    const [list, setCartItems] = useGlobalState("cartItems");
    
    useEffect(() => {
      const data = window.localStorage.getItem("literalcartting");
      if (data !== null) {
        setCartItems(JSON.parse(data));
      }
    }, []);
    
    useEffect(() => {
      window.localStorage.setItem(
        "literalcartting",
        JSON.stringify(list)
      );
    }, [list]);
    

    In the first useEffect I have added an empty dependency array [] so that this useEffect hook is renderd only one time.

    In the second one I have added [list] as a dependency array so the this useEffect hook only works only when there is some change in the list.

    Edit - Persisting data in localStorage

    Add this useEffect hook after the two hooks,

     useEffect(() => {
        return () => {
          window.localStorage.setItem("literalcartting", JSON.stringify(list));
        };
      }, []);