hi can you please explain why every time i add an item to local storage it gets updated instead of adding a new item ,,i guess for my code id isn't unique ,,,, but i can't understand how to fix it ....
here is code
https://jsfiddle.net/adulik/8sqbcox2/28/
//add task list item
function addTaskListItem(id) {
//get element by id
const task = document.getElementById(id);
let getItemFromStorage = localStorage.getItem("data-item")
if(!getItemFromStorage){
getItemFromStorage = JSON.parse(getItemFromStorage)
getItemFromStorage = [...getItemFromStorage,task.value]
console.log("storage",getItemFromStorage)
}else {
localStorage.setItem("data-item", JSON.stringify([task.value]))
}
}
I think you twisted your condition. It should be if(getItemFromStorage)
//add task list item
function addTaskListItem(id) {
//get element by id
const task = document.getElementById(id);
let getItemFromStorage = localStorage.getItem("data-item")
if(getItemFromStorage){ //modified the condition here from `!getItemFromStorage` to `getItemFromStorage`
getItemFromStorage = JSON.parse(getItemFromStorage)
getItemFromStorage = [...getItemFromStorage,task.value]
console.log("storage",getItemFromStorage)
localStorage.setItem("data-item", JSON.stringify(getItemFromStorage)) //update local storage with latest tasks
}else {
localStorage.setItem("data-item", JSON.stringify([task.value]))
}
}
It's working fine after that modification https://jsfiddle.net/n7Lj3zdx/
Because you update the "data-item", not append new data into it.
localStorage.setItem("data-item", JSON.stringify([task.value]))
It should be something like this:
localStorage.setItem("data-item", JSON.stringify([...ItemFromStorage].append(newItem))