Reputation: 13
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.
Upvotes: 1
Views: 2484
Reputation: 3
you can store your todo list array like this:
var todos= [{id:0},titile:"buy something"];
localStorage.setItem("todoList", JSON.stringify(todos));
and you can read data from local storage like this
var storedTodos = JSON.parse(localStorage.getItem("todoList"));
Upvotes: 0
Reputation: 64526
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
Upvotes: 1