useEffect do not listen for localStorage

冷暖自知 提交于 2020-12-09 07:29:32

问题


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 localStorage value with useEffect but after login and I'm getting 'undefined'. When localStorage value is updated useEffect do not run again and Spinner keeps spinning forever.

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

Only when I'm refreshing the page localStorage values appears 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;

回答1:


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

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

    if (item) {
      setUserData(item)
    }
  }

  window.addEventListener('storage', checkUsetData)

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



回答2:


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



来源:https://stackoverflow.com/questions/61178240/useeffect-do-not-listen-for-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!