How do I push data to localStorage

Following is my code

let bookData = [];

let title = document.getElementById('input-title');
let author = document.getElementById('input-author');
let pages = document.getElementById('input-pages');

function Book(BookTitle, BookAuthor, BookPages){
  this.title = BookTitle, = BookAuthor,
  this.pages = BookPages
// This function triggers when a button is clicked
function addNewBook(){
   let book = new Book(title.value, author.value, pages.value);
   let bookStringified = JSON.stringify(book);
   localStorage.setItem('data', bookData)

This code is saving bookData to the localStorage when I click the button. But when I reload the page and click the button again, then the data is overwritten and the previous data is lost.
I want the code to work such that when I reload the page and enter the details and click the button, the details should be added in the localStorage.
Can anyone tell why this is happening and fix the code so that it works perfectly

So you want to append data to the existing one as I understand. If that s the case you can use localStorage.getItem('data') push the existing data to your array, this you should do when your app loads so it’s initialized with the existing data from local storage and then you add new data to your array filled with the previous data and then you can save the modified array in localStorage with setItem .

Ok… so should I put localStorage.getItem('data') inside the window.onload() ??

You can do this when your app loads, I don t really know how complex your app is, but you can include that in a function that executes when your main page loads for example, or you create a function that does this and execute it. Just make sure you have access to that array so you can push data read from local storage.

can I use localStorage.getItem('data') inside the button clicked function

Yes, you should be able to do that, you can do it that way too if you want. Only one note. If you don’t have data for the first time in localStorage you might want to check for that too. I mean in case you manually clear the storage or in your code.

@Osiris can you send me code… i am not getting

hey @ved08 like osiris has said you need to add data back to your array on page reload also you should stringify the whole array not the data inside, here’s an example…

let data = localStorage.getItem("data");
let bookData = data ? JSON.parse(data) : []

document.getElementById('btn').addEventListener('click', addNewBook)

function addNewBook() {
  let book = new Book(title.value, author.value, pages.value);
  localStorage.setItem('data', JSON.stringify(bookData))


hope this helps :slightly_smiling_face:

Hey… when I console.log(bookData) is returning undefined

Can we see your updated code? Or even better put it on sandbox or something and give us the link.

1 Like

No need… I figured it out… But thanks for giving help