Struggling to make a todo-app function properly with localstorage, I'm a bit lost on the process. The app is built within a Vue.js project using a main.js file that connects two Classes: App.js and Todo.js (see below).
import App from "./classes/App.js";
const app = new App();
Here are the issues I've encountered:
- I can only seem to store one of my added todo's in my storage.
- I am unable to retrieve it from my storage and it doesn't load when I reload the page.
Any help would be greatly appreciated, I really want to understand this!
For a cleaner view, here's my CodeSandbox link: Link to my CodeSandbox
And below are the contents of the two js files: App.js
import Todo from "./Todo.js";
export default class App {
constructor() {
console.log("🍕");
this.setupEventListeners();
this.loadFromStorage();
}
setupEventListeners() {
console.log("👂🏽");
document
.querySelector("#add-item-text")
.addEventListener("keyup", this.createItem.bind(this));
}
createItem(e) {
if (e.key === "Enter") {
console.log("📕");
let inputText = document.querySelector("#add-item-text").value;
let todo = new Todo(inputText);
todo.add();
todo.saveToStorage();
this.reset();
}
}
loadFromStorage() {
const ref = localStorage.getItem("todo");
if (ref) {
todo = JSON.parse(ref);
}
}
reset() {
document.querySelector("#add-item-text").value = "";
}
}
Todo.js
export default class Todo {
constructor(title) {
this.title = title;
}
createElement() {
let li = document.createElement("li");
li.innerHTML = this.title;
if (li.innerHTML.includes("high:")) {
li.classList.add("prior-high");
} else if (li.innerHTML.includes("medium:")) {
li.classList.add("prior-medium");
} else if (li.innerHTML.includes("low:")) {
li.classList.add("prior-low");
} else {
li.classList.add("prior-medium");
}
li.addEventListener("click", this.markDone);
return li;
}
markDone(e) {
if (document.querySelector("li").classList.contains("done")) {
document.querySelector("li").remove();
window.localStorage.removeItem("li");
} else {
document.querySelector("li").classList.add("done");
}
}
add() {
let todo = this.createElement();
document.querySelector("#todo-list").appendChild(todo);
}
saveToStorage() {
let myStorage = window.localStorage;
myStorage.setItem("todo", JSON.stringify(this.title));
}
}