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
How to Render a Word Document (.Doc, .Docx) in the Browser Using JavaScript
Clear an Input Field With Reactjs
Disable Chrome Strict Mime Type Checking
How to Change the Font Color, Font Size, and Button Color in React
Creating a Leaderboard in Html/Js
Open Html5 Date Picker on Icon Click
How to Get Public User All Posts from Instagram, Without Instagram API
Append Data to Json Array Issue
How to Check Whether Session Is Null or Not in JavaScript
Localstorage Values Get Reset After Refreshing Page and Inserting New Values
How to Style HTML Select Option Hover and Selected Option Effects
How to Check If a Textbox Is Empty Using JavaScript
Jquery: Simplest Way to Check Url for a Parameter and Pass It to Anchor Href If It Exists
How to Use Aria-Expanded="True" to Change a CSS Property
Get the Contents of a Table Row With a Button Click