In order to save the to-dos in the local storage, I did the following.
I created an empty array.
const toDos = [];
Then, I pushed the newly created to-dos into the empty array.
toDos.push(newTodo);
Note: I saved the newly created to-dos in a variable by bringing the value of what was inputted.
const newTodo = toDoInput.value;
Next, I created a function to set an item in the local storage.
function saveTodos(){
localStorage.setItem(TODOSKEY, JSON.stringify(toDos));
}
-> I used JSON.stringify, because the local storage will save the array as a string if I don't do so. I needed it to be saved in a form of an array, so I had to stringify the array.
Next, I pressed play on the function that I just created.
saveTodos();
Next, I created a variable that has the value of what is in the local storage.
const savedToDos = localStorage.getItem(TODOSKEY);
The important (hard) part!
I created a conditional statement that if there's something saved in the local storage under TODOSKEY, console log.
if (savedToDos !== null) {
const parsedToDos = JSON.parse(savedToDos);
console.log (parsedToDos);
parsedToDos.forEach((item)=> console.log ("worked"));
}
-> if savedToDos is not null,
create a variable that changes the stringified array back into an array.
Then, console log the array.
Then, for each item of the array, console log "worked".
Note:
parsedToDos.forEach((item)=> console.log ("worked"));
will do the same as,
function A(item) {
console.log("worked")
}
parsedToDos.forEach(A)
** (item) is given for free in javascript!
Top comments (2)
Hello ! Don't hesitate to put colors on your
codeblock
like this example for have to have a better understanding of your code 😎Hey, thanks for the tip :)