Reputation: 1068
I have an Ionic app in which I store an Array with Native-Storage. This Array is an array of objects.
I stored it like this:
>>> array1: CertainType[] With at least 50 shuffled elements
this.nativeStorage.setItem('array1', { property: array1 })
.then(
() => { console.log('array1 stored') },
error => { console.log('array1 not Stored',error)
});
I retrieve the item like this:
this.nativeStorage.getItem('array1').then(
array1 => {
//On the Sucess of getting Array1 use it to create Array2
array2 = array1.splice(0,5); //<-- MY PROBLEM IS HERE
},
error => {
console.error('Error Getting Array', error);
}
);
I keep getting the Error of
I thought its because the process of storing and retrieving was messing with the type of the array, etc.
I tried to do casting:
..array1 as CertainType[]
-- EDITED>> I tried stringfying and JSONparsing.
this.nativeStorage.setItem('array1', { property: JSON.stringify(array1)}).then(. . . .
array2 = JSON.parse(array1);
Throw this error:
ERROR Error: Uncaught (in promise): SyntaxError: Unexpected token o in JSON at position 1
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
But i keep getting the same error on the splice().
If I not use the logic of storing, the code runs just fine.... Any clues. What am I missing? :/
Upvotes: 0
Views: 378
Reputation: 1068
The Ionic Native Storage Documentation confused me.
this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
I sticked to the book and use almost equal code on my app. But that word "property" over there was breaking my floor.
The good contributor above me, insisted (thank god) on the use of JSON.stringify
and JSON.parse
to save and retrieve the data.
So I did, but kept getting errors. Then I realized: when I tried to retrieve the data, my Array was stored on an Object. Ok! But UNDER a p-r-o-p-e-r-y attribute..
If I did get my array1 using array1.property I would get what I was looking for.
In the end, just a little change will make it work like a clock:
this.nativeStorage.setItem('array1', JSON.stringfy(array)})
.then(. . .
this.storage.get('array').then( array1 => {
console.log(JSON.parse(array1));
Upvotes: 0
Reputation: 2698
Use JSON stringify before store in localStorage cause it will return a promise just do this for example :
var test = { test: "thing", test2: "thing2", test3: [0, 2, 44] };
localStorage.setItem("test", JSON.stringify(test));
var test2 = localStorage.getItem("test");
test = JSON.parse(test2);
Upvotes: 2