'Todo app: getting todo-items in and out of localstorage
I was trying to get a todo-app to work from localstorage, but don't quite get how it's done. The app works through a Vue.js project with a main.js file where it is linked together from two Classes: App.js and Todo.js (watch below).
import App from "./classes/App.js";
const app = new App();
Here's a list of my findings:
- I can only get one of my added todo's into my storage?
- I don't seem to be able to return it from my storage? and also when I reload the page it's not getting loaded.
Thank you all ahead of time, it would mean a lot if I got to understand this!
I'll add my CodeSandbox link, since that will be more uncluttered to look at. Link to my CodeSandbox
And here's the two js files anyway: 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));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
