Reputation: 39
I have a form that whenever I add info it should keep it in localStorage so I cant then retrive it from a global variable.
But on refresh it only gives back the last input I did and its not really storing anything. help please
let todoList = [localStorage.getItem("list")] || [];
newTask.addEventListener("submit", addList)
function addList(e){
e.preventDefault();
let input = document.querySelector(".new-list input")
newListName = input.value;
input.value = ""
newTaskList.push(newListName)
//todoList.push(newListName)
localStorage.setItem("list", newListName);
}
Upvotes: 0
Views: 738
Reputation: 7831
Storing Your Array as a String
In order to use local storage with our array, we'll need to convert our array into a string using a method that makes it easy for us to unconvert later. The way convert an array into a string is by using the JSON stringify function.
Let's say you have the following array called movies:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
Using the stringify function, your movies array can be turned into a string by using the following syntax:
JSON.stringify(movies)
Since we want to store everything into our local storage, when you put it all together, you get the following:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
localStorage.setItem("quentinTarantino", JSON.stringify(movies));
Notice that my data is being stored under the key called quentinTarantino.
Retrieving Your Data
Storing your data is only part of the fun. A very important part of all this is being able to retrieve your data and get back to using it like an array. This involves first retrieving your data as a string:
var retrievedData = localStorage.getItem("quentinTarantino");
My retrievedData variable is storing the values returned by my local storage item whose key is quentinTarantino. This data is currently in the form of a string.
To convert from a string back to an object, use the JSON parse function:
var movies2 = JSON.parse(retrievedData);
Once you have done this, the movies2 variable will point to the parsed data which is, as you can guess, an array. You can call all of the array methods on your movies2 Array object just like you always would for any old array.
Upvotes: 1