skip to Main Content
import "./App.css";

import React, { useState, useEffect } from "react";
import Header from "../components/Header";
import AddContact from "../components/AddContact";
import ContactList from "../components/ContactList";

function App() {
  const LOCAL_STORAGE_KEY = "contacts";
  const [contacts, setContacts] = useState([]);
  const addContactHandler = (contact) => {
    console.log(contact);
    setContacts([...contacts, contact]);
  };
  useEffect(() => {
    const retrivedContacts = JSON.parse(
      localStorage.getItem(LOCAL_STORAGE_KEY)
    );
    if (retrivedContacts) setContacts(retrivedContacts);
  }, []);
  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
  }, [contacts]);

  return (
    <div className="ui container">
      <Header />
      <AddContact addContactHandler={addContactHandler} />
      <ContactList contacts={contacts} />
    </div>
  );
}

export default App;

I used the useEffect hook and stored the data in the storage but when it is reloaded it is getting lost and console logs are turning into an empty array
I tried to use the several methods i saw but did not work

2

Answers


  1. It’s possible that the local storage data is being cleared or overwritten when the page is reloaded. You can try a few things to avoid this issue:

    Check if there are any errors in the console that might be causing the data to be lost.
    Make sure that the "contacts" state is being correctly updated with the new contact information.
    Try using the useReducer hook instead of useState, as it provides more control over the state updates.
    Verify that the contacts array is not being cleared anywhere else in the code.

    Login or Signup to reply.
  2. State’s initial value is []

    const [contacts, setContacts] = useState([]);
    

    On reload when the following effect runs, it set an empty array in local storage.

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

    One solution is to set state initial value from localStorage like

    const [contacts, setContacts] = useState(() => JSON.parse(
          localStorage.getItem(LOCAL_STORAGE_KEY)
        ));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search