Localstorage Values Get Reset After Refreshing Page and Inserting New Values

after refreshing page and adding new values old localstorage values get erased

Every time you reload the page you're re-initializing favs instead of loading it from the localStorage so it's overwriting it when you save the first value. What you need to do is get the value from the localStorage first and then push the new value. You can do this on page load or when you first try to push the value to localStorage, like so:

let favs = [];

function addValue(e) {
if (e.target.value !== "") {
if (favs === []) {
favs = JSON.parse(localStorage.getItem("name"));
}

if (!favs.includes(e.target.value)) {
favs.push(e.target.value);
localStorage.setItem("name", JSON.stringify(favs));
console.log(favs);
document.getElementById("favsarray").innerHTML = favs
}
}
}

localStorage data keeps resetting on page reload - React js

The issue you were running into is that your useEffect to set the todos from the storage happens at a bad time in comparison with the one to set it.

So, instead of using an effect to grab the todos, get them synchronously with the state. This style of useState with a function argument, allows you to do a more expensive calculation for the initial creation of the state, so the function will only ever be called on initial component mounting.

  const [todos, setTodos] = useState(
() =>
JSON.parse(localStorage.getItem("todos")) || [
{ id: 123, text: "todo 1 demo" }
]
);
useEffect(() => {
localStorage.setItem("todos", JSON.stringify(todos));
}, [todos]);

In this way, you can get rid of the extra effect, and prevent a flash of incorrect UI between the initial code run and grabbing the todos from local storage.

https://codesandbox.io/s/eloquent-babycat-z86dts?file=/src/App.js

local storage resets after reload

LocalStorage only stores string, you need to stringify the array before storing and Parse it before reading.

let movies =  JSON.parse(localStorage.getItem('movies')) || [];

//saving to localStorage:

localStorage.setItem('movies', JSON.stringify(movies) );



Related Topics



Leave a reply



Submit