localStorage For Saving Tasks Of To-Do List

Issue

I have a to-do list which I’m making, everything is working fine.
I just have one problem with the saving.

Everytime I reload or close the page, all the data/tasks are removed. To prevent this, I want to use localStorage.

How am I supposed to do this?

Maybe save all the tasks right before the page is closed or reloaded. And when the page is loaded again, get all the data back, as it was.

Solution

Saving should be done whenever you add, remove or make a change to a todo. You can use localStorage.setItem(). If you have a JavaScript object or array of todos then you can JSON encode the data to be stored, because localStorage is a simple key-value pair structure for strings.

localStorage.setItem('todos', JSON.stringify(yourVariable));

On page load, you should read the todos from local storage and decode it:

let todos = [];
const todosJson = localStorage.getItem('todos');
if(todosJson){
    todos = JSON.parse(todosJson);
}
// run code which adds UI elements for the todos

Answered By – MrCode

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.