Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - 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 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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
  }
}, [])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...