Sausejii
Sausejii

Reputation: 63

Array is null when trying to use .push after localstorage

I get a TypeError saying my array is null when I try to push a new value into it.

//first off..
var sillyArray= ["dummy"];
localStorage.setItem("sillyArray", JSON.stringify(sillyArray));

//I later used this
sillyArray = JSON.parse(localStorage.getItem("sillyArray"));
//the error is here
sillyArray.push("yes");
localStorage.setItem("sillyArray", JSON.stringify(sillyArray));

Am I unable to push or parse this?

(Edited a posting error)

Upvotes: 0

Views: 123

Answers (3)

Sausejii
Sausejii

Reputation: 63

As user nnnnnn said, I hadn't properly executed mylocalStorage.setItem("sillyArray", JSON.stringify(sillyArray));

It was sitting in an if statement (not pictured) that wasn't executing causing the null.

Thanks guys!

Upvotes: 0

Mati
Mati

Reputation: 1148

Yes, you can but you are trying to push an item into a undefined var, this is why you get a TypeError.

Here is how you should do that:

var array = ['dummy'];
localStorage.setItem('someKey', JSON.stringify(array));
array = JSON.parse(localStorage.getItem('someKey'));
array.push('foo');
localStorage.setItem('someKey', JSON.stringify(array));

then if you do

console.log(JSON.parse(localStorage.getItem('someKey')))

the output will be what you are expecting ["dummy", "foo"]

Upvotes: 0

Captus
Captus

Reputation: 71

The yesArray was never definded. That's why it's impossible to .push().

Upvotes: 2

Related Questions