Skip to content Skip to sidebar Skip to footer

Useeffect Does Not Listen For Localstorage

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 tryin

Solution 1:

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

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

    if (item) {
      setUserData(item)
    }
  }

  window.addEventListener('storage', checkUserData)

  return() => {
    window.removeEventListener('storage', checkUserData)
  }
}, [])

Solution 2:

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

Solution 3:

The solution is to use this structure:

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

    return() => {
      // When the component unmounts remove the event listenerwindow.removeEventListener("storage");
    };
}, []);

Solution 4:

  • "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.

constMain = () => {
  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.

Post a Comment for "Useeffect Does Not Listen For Localstorage"