const [contacts, setContacts] = useState([]);
//Fetch the Value from Local Storage
useEffect(() => {
const retrieveContacts = localStorage.getItem(LOCAL_STORAGE_KEY);
if (retrieveContacts) {
setContacts(JSON.parse(retrieveContacts));
}
}, []);
//Storage the Value
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);
i tried to fetch data from local storage but it's not working
CodePudding user response:
The use of useEffect
hooks is the issue. At the second useffect
setting the 'contacts' s not happeing since the first one hasn't yet been set. So the value of setting the localstorage goes null. Instead have the value set at the point of useState hooks. Also, when you are using localStorage
, it's important to handle the initial state as well. Try the code below.
import React from 'react'
import { useState, useEffect } from 'react';
const App2 = () => {
const LOCAL_STORAGE_KEY = 'key-1'
const [contacts, setContacts] = useState(
localStorage.getItem(LOCAL_STORAGE_KEY) ? JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) : {name:'james', count:0}
);
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);
const handleButtonClickEvent = () => {
setContacts({name:'james', count:contacts.count 1})
}
return (
<>
<div>Name: {contacts.name}</div>
<div>Country: {contacts.count}</div>
<input type='button' value='button' onClick={(e) => handleButtonClickEvent()}></input>
</>
)
}
export default App2
CodePudding user response:
Your local storage will be empty after every reload because your default 'contacts' value is an empty array. Your second useEffect
then saves this empty array to local storage when the component mounts, overwriting whatever value was previously saved there.
You can resolve this by getting rid of your first useEffect
, and loading the default 'contacts' value from local storage:
const retrieveContacts = () => localStorage.getItem(LOCAL_STORAGE_KEY) || []; // Outside of component
...
const [contacts, setContacts] = useState(() => retrieveContacts()); // Inside of component
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);