Home > Blockchain >  children component value reset when reload page in react
children component value reset when reload page in react

Time:04-12

when I reload the page usestate become null but I want when i reload the page all div are appear there. I use the local-storage but when I reload it also become null code:-

        const [item, setItem] = useState([]);
    const handleClick = (val, id) => {
    
            localStorage.setItem('ChannelName', val)
            setActiveIndex(val);
            let text = val;
            let index = id;
    
            setItem(prev => {
                if (prev.some(({ index }) => (id === index))) return prev;
                else {
                    // console.log("prev",prev);
                    return [...prev, { val: text, index: index }];
                }
            });
        };
return(
      <div className="allDivs">
                {item && item.map((items, index) => {
                    return (
                        <div key={index} >
                            <TabHeader item={items}  itemList={item} />
                            

                        </div>
                    )
                })}
            </div>

) When I click the RundownList div is appear but reload the page then I again start from clicking the rundown list

is this possible that when user reload then also div appear/useState not become null

CodePudding user response:

You need to make sure that there is a useEffect with an empty dependency list that when the component loads it checks if here is something in localstorage. If there is it uses that.

You're not checking in this code if local storage already exists.

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

    if (item) {
      setUserData(item)
    }
  }

  window.addEventListener('storage', checkUserData)

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

Reference:

useEffect does not listen for localStorage

  • Related