Search code examples
javascriptreactjslocal-storage

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


Solution

  • 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