so i want to make a page that render a data from localStorage, i want to make it realtime, so if i wanti to delete some data from localStorage the UI of deleted data removed realtime
This is my code, but it does not realtime, i need to reload to look the changes
const [favoritesPkg, setFavoritesPkg] = useState([]);
useEffect(() => {
let a = JSON.parse(localStorage.getItem("savedPkg"));
setFavoritesPkg(a);
}, []);
const handleRemoveAll = () => {
localStorage.removeItem("savedPkg");
};
return (...)
I also try this code, i show what i expected but there is an error: maximum depth render
const [favoritesPkg, setFavoritesPkg] = useState([]);
useEffect(() => {
let a = JSON.parse(localStorage.getItem("savedPkg"));
setFavoritesPkg(a);
}, [favoritesPkg]);
const handleRemoveAll = () => {
localStorage.removeItem("savedPkg");
}
so in my component there is an action button like edit, and delete…i want if i delete single component from data in localStorage will disappear realtime, so i do not need refresh my page to see that changes
2
Answers
For fixing this you need to update handleRemoveAll function. In this function you are only removing the item from localstorage. You are not updating the state. Please update the function as follow.
And also update the useEffect to this
This will surely update the UI in realtime.
First you need to understand one thing: React only rerenders when you update a stateful variable.
Stateful variables are those created with useState, useReducer or an external library such as Redux, Jotai, Mobx, etc…
Second thing is, if you have a useEffect where you update a variable and you look for the variable inside the dependency array, you will end up in a loop.
So NEVER do something like you are doing in your seconde code example
To achieve the result, you want change your code adding a
setFavoritesPkg
inside thehandleRemoveAll
function.Your code should look like this:
If you want to update something in the screen (trigger a re-render) update the state variable, localStorage is not observed by react to update the dom.