2

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

Meta Boost
  • 33
  • 4
  • Does this answer your question? [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) – Liam Apr 28 '22 at 08:16
  • @Liam I am already using same like this but some how its getting to default value , not sure why its happening – Meta Boost Apr 28 '22 at 08:25
  • Please add some debugging details. Do you see the values in the dev tools? Can you log them? You should add `console.log` before `localStorage.setItem`. – jabaa Apr 28 '22 at 08:35
  • @jabaa added screen shot of react devtools. value is saving to localstorage but when I refresh local storage the value become empty object – Meta Boost Apr 28 '22 at 08:50
  • Have you added the `console.log` statements? – jabaa Apr 28 '22 at 08:56
  • @jabaa added console unable to open console for the one before localStorage.setItem – Meta Boost Apr 28 '22 at 09:02
  • I have no idea, what this means. Could you please not add screenshot of log output? And add some description. – jabaa Apr 28 '22 at 09:05
  • @jabaa [ { "username": "vxvx", "email": "gfhgf" } ] useEffect(() => { console.log(contacts) // localStorage.setItem(keyy, JSON.stringify(contacts)); localStorage.setItem(keyy , JSON.stringify(contacts)); }, [contacts]) – Meta Boost Apr 28 '22 at 09:05
  • I see empty arrays in your log. Does it mean, you're resetting the local storage on init? – jabaa Apr 28 '22 at 09:07
  • @jabaa actually when app starts there is no data , when we add data it will save to local storage and will be populated in the list. updated the description – Meta Boost Apr 28 '22 at 09:13

1 Answers1

4

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)
  }, [])
jabaa
  • 5,844
  • 3
  • 9
  • 30