18

I'm making an authentication system and after backend redirects me to the frontend page I'm making API request for userData and I'm saving that data to localStorage. Then I'm trying to load Spinner or UserInfo.

I'm trying to listen for the localStorage value with useEffect, but after login I'm getting 'undefined'. When the localStorage value is updated useEffect does not run again and Spinner keeps spinning forever.

I have tried to do: JSON.parse(localStorage.getItem('userData')), but then I got a useEffect infinite loop.

Only when I'm refreshing the page does my localStorage value appear and I can display it instead of Spinner.

What I'm doing wrong?

Maybe there is a better way to load userData when it's ready?

I'm trying to update DOM in correct way?

Thanks for answers ;)

import React, { useState, useEffect } from 'react';
import { Spinner } from '../../atoms';
import { Navbar } from '../../organisms/';
import { getUserData } from '../../../helpers/functions';

const Main = () => {
  const [userData, setUserData] = useState();
  useEffect(() => {
    setUserData(localStorage.getItem('userData'));
  }, [localStorage.getItem('userData')]);

  return <>{userData ? <Navbar /> : <Spinner />}</>;
};

export default Main;
0

4 Answers 4

41

It would be better to add an event listener for localstorage here.

useEffect(() => {
  function checkUserData() {
    const item = localStorage.getItem('userData')

    if (item) {
      setUserData(item)
    }
  }

  window.addEventListener('storage', checkUserData)

  return () => {
    window.removeEventListener('storage', checkUserData)
  }
}, [])
11
  • 8
    To extend on this answer: The reason OPs example doesn't work is because the dependency array passed to useEffect determines whether or not to re-run the effect when the component is rendered, which means that while the effect would re-run if localStorage changed, it would have to render first. The way around this is to set up a subscription to localStorage, as Minan does, to watch for changes and notify the component to re-render.
    – Dan
    Apr 12, 2020 at 21:29
  • hi, can you please help me with this? stackoverflow.com/questions/62906923/…
    – jason1234
    Jul 15, 2020 at 3:54
  • What about this? Doesn't that mean that the eventListener wouldn't be triggered in the tab changing the storage?
    – A. Rabus
    Nov 13, 2020 at 11:22
  • Actually, it doesn't work like that. As you can see in this example demo, all values continue to work synchronously. Demo => mq4uu.csb.app Code => codesandbox.io/s/bold-rain-mq4uu
    – Minan
    Nov 13, 2020 at 22:32
  • 1
    @Minan I am having a hard time reproducing this logic in a project, not sure why the event listener on storage doesn't react to removeItem event, added a second button to your sandbox: codesandbox.io/s/elegant-star-yw1z5 Apr 9, 2021 at 21:35
11

Event listener to 'storage' event won't work in the same page

The storage event of the Window interface fires when a storage area (localStorage) has been modified in the context of another document.

https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event

5

The solution is to use this structure:

useEffect(() => {
    window.addEventListener("storage", () => {
      // When storage changes refetch
      refetch();
    });

    return () => {
      // When the component unmounts remove the event listener
      window.removeEventListener("storage");
    };
}, []);
-1
  • "Maybe there is a better way to load userData when it's ready?"

You could evaluate the value into localStorage directly instead passing to state.

const Main = () => {
  if (localStage.getItem('userData')) {
    return (<Navbar />);
  }
  else {
    return (<Spinner />);
  }
};

If there is a need to retrieve the userData in more components, evaluate the implementation of Redux to your application, this could eliminate the usage of localStorage, but of course, depends of your needs.

4
  • In that way it catches "undefined" value(and the spinner will spin forever). When after few seconds value "undefined" is updated, it will not update DOM. Apr 12, 2020 at 21:43
  • Interesting... Try to pass the userData as a props to the Main component. Apr 12, 2020 at 21:48
  • This makes a thread-blocking read into localstorage on every re-render, so beware of that
    – hakazvaka
    Dec 25, 2020 at 8:42
  • 1
    @hakazvaka Using IndexedDB could solve this? Knowing that works asynchronously... Dec 25, 2020 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.