Home > Back-end >  ReactJS localstorage.getItem is not working
ReactJS localstorage.getItem is not working

Time:06-13

i have a problem with the localstorage.getItem, the setItem function is working fine and the data is stored correctly but when i refresh the page the data is gone. Here is my codes

  useEffect(()=>{
localStorage.setItem(local_Storage_key, JSON.stringify(contacts));
}, [contacts]);

 useEffect(()=>{
    const storage = JSON.parse(localStorage.getItem(local_Storage_key));
    if (storage) {setContacts(storage);}
    }, []);

picture of the localstorage before i refresh the page

CodePudding user response:

I think that's because your below code is executing after component has been mounted.

useEffect(()=>{
    localStorage.setItem(local_Storage_key, JSON.stringify(contacts));
}, [contacts]);

And because of this it is setting the initial value of contacts into the localStorage again. To avoid this you can set the initial value of contacts to the value you get from the localStorage

const [contacts,setContacts] = useState(JSON.parse(localStorage.getItem(local_Storage_key)));

useEffect(()=>{
    localStorage.setItem(local_Storage_key, JSON.stringify(contacts));
}, [contacts]);

// remove another useEffect

CodePudding user response:

I suggest you use useLocalStorage

import { useLocalStorage } from 'react-use';

const Demo = () => {
  const [value, setValue, remove] = useLocalStorage('my-key', 'foo');

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue('bar')}>bar</button>
      <button onClick={() => setValue('baz')}>baz</button>
      <button onClick={() => remove()}>Remove</button>
    </div>
  );
};
  • Related