0

I am trying to use save some data in localstorage. Here I am trying ,

let marks = localstorage.getItem('marks') || [] 

Here Now, I am trying to add elements into this array using some action.

const addMarks = () => {
  
localstorage.setItem('marks', ['10'])   

}

Then I am using this variable to render the marks like

marks.map((index, mark) => {

  return <h1>mark</h1>

})

But this way it does not work as localstorage only supports the string as a value.

How do I implement this ?

ganesh kaspate
  • 1
  • 9
  • 41
  • 88
  • 1
    Does this answer your question? [How do I store an array in localStorage?](https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage) – bill.gates Oct 23 '20 at 10:45

3 Answers3

0

Serialize it JSON.stringify() and parse it back Parse

Robert
  • 2,538
  • 1
  • 9
  • 17
0

localStorage only support strings as values, you'll have to JSON.stringify your objects when saving them and JSON.parse them when retrieving them

let marks = JSON.parse(localstorage.getItem('marks')) || [];

const addMarks = () => {
  localstorage.setItem('marks', JSON.stringify(['10']))   
}
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
0

Have you tried to just use the .split() method? If you make an array ['10', '9', '8'], you will get '10,9,8'. Just use .split(',') and you will get an array!

localStorage.getItem('marks').split(',')