DEV Community

ghandicode
ghandicode

Posted on • Updated on

Saving in local storage

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));
}
Enter fullscreen mode Exit fullscreen mode

-> 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"));
}
Enter fullscreen mode Exit fullscreen mode

-> 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)
Enter fullscreen mode Exit fullscreen mode

** (item) is given for free in javascript!

Top comments (2)

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
ghandicode profile image
ghandicode

Hey, thanks for the tip :)