'Local storage not working to store created Task List
I have created local storage in two functions, one function sets the local storage with the storage key and the second function gets the storage key, but it's not working.
I have tied the local storage function with the createTask function because that is where the tasks are being created.
The outcome should be that the local storage keeps the list of tasks created by the user when the browser refreshers, I want to use local storage in this case.
JS code
const STORAGE_KEY = "task-list-storage-key";
/**********************************************
* function that creates the HTML elements *
**********************************************/
const createTask = () => {
const id = createId()
const task = elements.input.value;
const date = elements.cal.value;
if(!task && !date) return alert("Please fill in task and select date");
if(!task) return alert("Please fill in task");
if(!date) return alert("Please select date");
const tasks = document.createElement("div");
tasks.innerHTML = `
<button class = "sort">Sort</button>
<div class="task" data-id = "${id}">
<div class="content">
<input type ="checkbox" class="tick">
<input type ="text" class = "text" id = "text" value="${task}" readonly>
<label class = "due-date" for ="text">${date}</label>
<input type ="date" class = "date" id = "date">
</div>
<div class = "actions">
<button class="edit" data-id="${id}">Edit</button>
<button class="delete" data-id="${id}">Delete</button>
</div>
</div>
`
elements.list.appendChild(tasks)
markOfdddueDate()
return tasks
}
/*********************************
* Storing tasks in local storage*
*********************************/
function Storingtasks(){
localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks))
createTask(tasks)
}
function getStoredtask(){
const storedkey = localStorage.get(STORAGE_KEY);
if(storedkey){
tasks = JSON.parse(storedkey);
createTask(tasks)
}
}
getStoredtask()
Solution 1:[1]
You made mistake. Should be:
function getStoredtask(){
const storedkey = localStorage.getItem(STORAGE_KEY);
if(storedkey){
tasks = JSON.parse(storedkey);
createTask(tasks)
}
}
And yes look at the comment under initial post. You have to call function to store them also. And you made error there too:
Should be:
function Storingtasks(){
localStorage.setItem(STORAGE_KEY, JSON.stringify(createTask(tasks)))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
