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);
2
Answers
this is everything so far:
the infinite loop is gone, but still state is not saved when I refresh. I checked the local storage and indeed the array saved gets wiped out the moment I refresh the page. Any fix?
And thank you a lot for the help + thought I might add the functions where I alter the array.
Your code have the problem of infinite rendering, there is no dependency array in both of the
useEffect
hooks,Try this code,
In the first
useEffect
I have added an empty dependency array[]
so that thisuseEffect
hook is renderd only one time.In the second one I have added
[list]
as a dependency array so the thisuseEffect
hook only works only when there is some change in thelist
.Edit – Persisting data in localStorage
Add this useEffect hook after the two hooks,