loading...

re: Next.js persistent state with React hooks and localStorage. How to make it work? VIEW POST

FULL DISCUSSION
 

Hello Klaudiusz!

I found your thread on Google trying to solve mine 😂

I don't have a similar issue but I successfully did something similar, I figure, it's better that I post it than not at all.

export const PostsContextProvider = ({ children, storageKey = "posts" }) => {
  const [isInitialized, setIsInitialized] = useState(false);

  const [posts, dispatchPost] = useReducer(reducer, []);

  useEffect(() => {
    if (isInitialized) {
      localStorage.setItem(storageKey, JSON.stringify(posts));
    }
  }, [posts]);

  useEffect(() => {
    dispatchPost({
        type: SET_POSTS,
        value: JSON.parse(localStorage.getItem(storageKey)) || []
      });

    setIsInitialized(true);
  }, []);

  return (
    <PostsContext.Provider value={{ posts, dispatchPost }}>
      {children}
    </PostsContext.Provider>
  );
};

As you can see, my version use 2 useEffect. One to initialized the data using the localStorage if it's there is something (otherwise, it defaults to []) and one to keep the localStorage updated with the app.

Happy to answer question if you have some 👍

code of conduct - report abuse