mm1975
mm1975

Reputation: 1655

Store JSON to localstorage not working

After pushing a button I would like to save an item (nested JSON) into a new Array and store it to the localstorage.

addFavourite(card) {
    console.log(JSON.stringify(card));
    var cards = [];
    this.cardfavouriteArray.push.apply(cards, card)
    this.storage.set('favouriteData', this.cardfavouriteArray);
    }


getData() {
    var data = this.storage.get('favouriteData');
    if(data){
      this.storage.get('favouriteData').then((val) => {
        console.log('test', JSON.stringify(val));
      });
    }

I get no error, but 'test' is always empty. I need it as an array.

Upvotes: 1

Views: 3325

Answers (3)

Komal
Komal

Reputation: 1097

Set array in local storage like this:

localStorage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));

Get array from local storage like this:

var data = JSON.parse(localStorage.getItem('favouriteData'));

Explanation: It is because localstorage can not store object, it stores in string format. So we need to JSON.stringify the object. Also localStorage has function name setItem and getItem as defined here: http://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage. When we get the string from localstorage, we need to JSON.parse to convert it back to object.

You are using this.storage.set and this.storage.get. It is not clear which library are you using, but the code I mentioned will work in Angular or any framework. Since localStorage.setItem and localStorage.getItem is pure javascript.

Upvotes: 0

NullPointer
NullPointer

Reputation: 7368

Set and Get method for localstorage varies on which service you are using

1.HTML5 localStorage- If you are using HTML5 localStorage directly then you should use localStorage.getItem and localStorage.setItem

2.localstorage is limited to store only string key/value pairs.Use JSON.stringify and JSON.parse when using setting and getting from localstorage

addFavourite(card) {
    console.log(JSON.stringify(card));
    var cards = [];
    this.cardfavouriteArray.push.apply(cards, card)
    this.storage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
    }


getData() {
    var data = this.storage.get('favouriteData');
    if(data){
      this.storage.getItem('favouriteData').then((val) => {
        console.log('test', JSON.parse(val));
      });
    }

3.ng2-webstorage- In case of ng2-webstorage this.storage.retrieve and this.storage.store will work.

Upvotes: 3

Gijs Post
Gijs Post

Reputation: 199

Change this.storage.set('favouriteData', this.cardfavouriteArray); to localStorage.set('favouriteData', JSON.stringify(this.cardfavouriteArray)); (It's a pre-defined method by angular). Also stringify the array.

Upvotes: 0

Related Questions