LocalStorage.getLocalStorage is not a function - JS DOM Manipulation
I am creating a program where I am storing the data in local storage. Anytime I click on the add/remove button, I keep getting this error. LocalStorage.getLocalStorage is not a function
Below is my Local Storage class
class LocalStorage {
constructor(storageKey) {
this.storageKey = storageKey;
}
getLocalStorage = () => JSON.parse(localStorage.getItem(this.storageKey));
setLocalStorage = (data) => localStorage.setItem(this.storageKey, JSON.stringify(data));
}
export default LocalStorage;
I'm importing this class in this code block below
class SaveAll {
save = (title, author) => {
let books = [];
if (localStorage.getItem('book') === null) {
books = [];
} else {
// books = JSON.parse(localStorage.getItem('book'));
books = LocalStorage.getLocalStorage('books');
}
const book = { text1: title, text2: author };
books.push(book);
// localStorage.setItem('book', 开发者_JAVA技巧JSON.stringify(books));
LocalStorage.setLocalStorage(books);
}
}
This is the extracted code for the UI
static renderBooks = () => {
bookText.innerHTML = '';
let books = [];
if (localStorage.getItem('book') === null) {
books = [];
} else {
books = JSON.parse(localStorage.getItem('book'));
books.forEach((book) => {
bookText.innerHTML += `
<div class="wrapper">
<p class="book-title">${book.text1}</p>
<p class="book-author">${book.text2}</p>
<button onclick="deleteBook('${book.text1}',
'${book.text2}')">Remove</button>
</div>
`;
});
}
}
I have tried implementing the code in the home.html file but it didn't work so I opted to extract them into a separate js files and that is still not working
you are trying to access class methods without class instance so i suggest make your methods static
class LocalStorage {
constructor(storageKey) {
this.storageKey = storageKey;
}
static getLocalStorage = () => JSON.parse(localStorage.getItem(this.storageKey));
static setLocalStorage = (data) => localStorage.setItem(this.storageKey, JSON.stringify(data));
}
this will solve your problem because static methods are accessible without class instance
精彩评论