#Cannot store data to the localScorage

5 messages · Page 1 of 1 (latest)

worn tide
#

#🚀︱start-here
In my project, I would like to store data to the localStorage.

I would like the data to be stored as array of objects.

Initially, my data is empty array, like this:

data = [];

Then I am putting an object inside it (using push() method), like this:
localStorage.setItem("scores", this.data.push({name:"someName", score: 4}))
and I am getting the following:
[ { name: "someName", score: 4 } [
Until now everytghing is OK.

Then I want to push another object to the data property.

I am doing the following:
localStorage.setItem("scores", this.data.push({name:"anotherName", score: 1})).
Now instead array with two objects, I am getting array with one object (only the last one).

I am geting this:
[ { name: "anotherName", score: 1 } ]
I tryed to use spread operator to add second object to the data array, but I am still getting the same result.

I should get array with two objects, but I am getting array with one object. Why?

quick hound
#

I'm not sure how that stores even one correct object. The return value of an array push is the length of the array, so the value stored in localStorage should actually just be a number and both the array and last object would not be there. It seems that you are trying to do too many things in one statement. The normal approach would be to push the item to the array first. After that, the stringified array is stored in localStorage. I noticed that you also did not stringify your data. The fact that you have any data in local storage that even looks like what you tried to store suggests the probability that you have other code doing the actual storing.

worn tide
#

I tryed to stringify the data - still getting the same problem. As a result I am getting [Object, Object], but I cannot access to any property of this object.

quick hound
worn tide
#

Yes of course, I used JSON. stringify(), too