Try this, with added comments for an explanation of how it works.
var bookobj = {
Name: name,
Author: author,
Edition: edi,
Price: pri,
}
// read what the 'books' value currently is
// the `|| '[]'` makes it so that, if it's null, it defaults to a string of an empty array
// which, when passed to JSON.parse, turns into an empty array
var books = JSON.parse(localStorage.getItem('books') || '[]')
// add the book object to the temporary books variable
books.push(bookobj)
// re-save it back to local storage
localStorage.setItem('books', JSON.stringify(books))
Your current code doesn't work because:
The if (localStorage === null)
line doesn't actually check for the variable in local storage. To do that, you'd do if (localStorage.getItem('...') === null)
. However, I've opted to use ||
in my solution for cleanliness.
Creating the array every time and saving it will continually overwrite the array that's in storage, instead of reading and adding to what's already in storage.
In the first part of the if
statement, the array isn't actually saved to storage, only the bookobj
itself.