I have created a basic todo list where I am facing an issue. When I add an item like "wash dishes" through the input, it displays correctly. However, upon refreshing the page and accessing the object in the array from local storage, I get back {"TODO_ITEM:1":"wash dishes"}. I believe there is a mistake in how I am accessing the data. I have tried various methods found online but none seem to work properly. This is one of my first coding projects, so any advice or suggestions would be greatly appreciated!
//Selecting elements
const list = document.querySelector('#todo-list');
const form = document.querySelector('#create-todo');
const input = document.querySelector('#new-todo');
let todoCount = 1;
let obj = {};
let todo = [];
// Listens for click events on list items and buttons
list.addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
e.target.classList.toggle('done');
} else if (e.target.tagName === 'BUTTON') {
e.target.parentElement.remove();
}
})
// Handles form submission to create a new todo
form.addEventListener('submit', function(e) {
// Prevent default form submission
e.preventDefault();
// Add todo item to local storage
addToLocalStorage(todo)
// Create new list item with button
createLi()
console.log(localStorage)
})
// Fetches data from local storage
function getFromLocalStorage() {
const reference = localStorage.getItem('TODO_LIST')
if (reference) {
todo = JSON.parse(reference)
renderTodo(todo)
}
}
// Function to create a new list item
function createLi() {
const newLi = document.createElement('li');
const newBtn = document.createElement('button');
newLi.innerText = input.value;
list.append(newLi);
newBtn.innerText = 'Remove';
newLi.append(newBtn);
input.value = '';
}
// Function to add item to local storage
function addToLocalStorage(todo) {
let obj = {}
let key = 'TODO_ITEM:' + todoCount
console.log(obj)
todoCount++
obj[key] = input.value
todo.push(obj)
localStorage.setItem('TODO_LIST', JSON.stringify(todo))
}
// Function to keep todo list displayed after refresh
function renderTodo() {
list.innerHTML = '';
for (let i = 0; i < todo.length; i++) {
console.log(todo[i])
let indx = todo[i]
const newLi = document.createElement('li');
const newBtn = document.createElement('button');
newLi.innerText = JSON.stringify(indx);
list.append(newLi);
console.log()
newBtn.innerText = 'Remove';
newLi.append(newBtn);
console.log(indx)
}
}
getFromLocalStorage();