Reputation: 51
ı am set items to local storage , and getting from local storage, when set item to local storage it work, but when ı refresh page all ıtem ın the local storage it disappearing.
//* local storage get notes
React.useEffect(()=>{
const localNotes=JSON.parse(localStorage.getItem('react-note-app-data'));
if(localNotes){
setNoteData(localNotes)
}
},[])
//* local storage set notes
React.useEffect(()=>{
localStorage.setItem('react-note-app-data',JSON.stringify(noteData))
},[noteData])
Upvotes: -1
Views: 93
Reputation: 725
When you are setting in local storage, give a check whether noteData is there or not. Because useEffect always run after render and then next it will run when any of its dependency get change, Try below code might it fix the issue for you
//* local storage get notes
React.useEffect(()=>{
const localNotes=JSON.parse(localStorage.getItem('react-note-app-data'));
if(localNotes){
setNoteData(localNotes)
}
},[])
//* local storage set notes
React.useEffect(()=>{
if (noteData) { // added if check, to check wether noteData variable has value if yes then set the value in localStorage else not.
localStorage.setItem('react-note-app-data',JSON.stringify(noteData))
}
},[noteData])
Upvotes: 1