'local storage is not persistent in react app

I am creating a react app which is using local storage. I am saving and array of objects to local storage.

when I try to save to local storage the data is saving. and then when I refresh the page the saved data is becoming empty object, like this [].

if any one knows why its happening please help me

import React, {useEffect, useState} from 'react';
import Addcontact from './Addcontact';
import './App.css';
import Contactlist from './Contactlist';
import { Header } from './Header';

function App() {
const keyy ="contactlist"
  const [contacts, setcontacts] = useState([])
 const contactshandler = (contact)=> {
   console.log(contact)
   setcontacts([...contacts, contact])
 }


 useEffect(() => {
  const getdata = JSON.parse(localStorage.getItem(keyy))
  getdata && setcontacts(getdata)
  }, [])

  useEffect(() => {
    localStorage.setItem(keyy, JSON.stringify(contacts));
    }, [contacts])
   
  return (
    <div className="ui container">
      <Header />
      <Addcontact contacts={contacts} contactshandler={contactshandler} />
      <Contactlist contacts={contacts} />
    </div>
  );
}

app component

import React, { useState } from 'react'

function Addcontact({contacts, setcontacts, contactshandler}) {
    const [user, setuser] = useState({username:'', email:''})

 const addvalue = (e) => {
    e.preventDefault();
    console.log(user)
    contactshandler(user)
    setuser({username:'', email:''})

}
    return (
        <div>
            <div className='ui main'>
                <h2> Add Contact</h2>
                <form className='ui form' onSubmit={addvalue}>
                    <div className=''>
                        <label>name</label>
                        <input name="name" placeholder='name' value={user.username} onChange={(e) => setuser({...user, username : e.target.value })} />
                    </div>
                    <div className='feild'>
                        <label>email</label>
                        <input email='email' placeholder='email' value={user.email} onChange={(e) => setuser({...user, email: e.target.value})} />
                    </div>
                    <button>add</button>
                </form>
            </div>
        </div>
    )
}

export default Addcontact

export default App;

add component

this is the value showing when saving after refresh this value becomes empty object

enter image description here

console enter image description here



Solution 1:[1]

You don't need useEffect to read the data. You can initially read it.

const [contacts, setcontacts] = useState(JSON.parse(localStorage.getItem(keyy)) ?? [])

and remove

 useEffect(() => {
  const getdata = JSON.parse(localStorage.getItem(keyy))
  getdata && setcontacts(getdata)
  }, [])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jabaa