Ali
Ali

Reputation: 87

ReactJS localstorage.getItem is not working

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

Upvotes: 0

Views: 3353

Answers (4)

Rahil Khosravi
Rahil Khosravi

Reputation: 1

i removed the < React.StrictMode >< React.StrictMode /> from index.js and defined the useEffect for getItem before the useEffect for set item and it worked correctly

Upvotes: 0

Mohsen
Mohsen

Reputation: 11

I have been wondering about the same problem for several days. Finally I found a solution to the problem:

If you remove the StrictMode element from index.js file, the problem will be solved, and the localStorage data will persist when refreshing the page. Best

Upvotes: 0

Rohan Veer
Rohan Veer

Reputation: 1490

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

Upvotes: 3

tszhong0411
tszhong0411

Reputation: 195

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>
  );
};

Upvotes: 1

Related Questions