Appropriate Local Storage for Ionic

Hallo,

I am reading about Local Storage and I am quite confused. As I see there are two options:

  1. Native Storage , import { NativeStorage }
  2. Ionic Storage, import { IonicStorageModule }

My app is developed with Ionic 3 and I am trying to save an array of object localy after retrieve it from Parse Server.

With Ionic 1 I stored the objects array like this:

setUsers (users){
        window.localStorage.users_data = JSON.stringify(users);
    }
    getUsers(){
       return JSON.parse(window.localStorage.users_data || '[]');
    }

So now, what is the best option to save my data and stringfy them and parse them?

Thank you a lot

Hi

Ionic Storage I would say. Until you have reasons to ditch it.

Regards

Tom

Thank you Tommertom

I will go with Ionic Storage. Can you clarify me a little how to use it to stringify data and parse data?

How my functions will be?

Thank you

Hi
there will be no need to stringify

Just check the examples on https://ionicframework.com/docs/storage/

And make sure you check on storage.ready before accessing the magic

For persistence sake, use the sqlite plugin.

Regards
Tom

I am reading the docs but I cannot figure out…

I used this one for my data

setUsers (users){
        window.localStorage.users_data = JSON.stringify(users);
    }

how it will be for the Ionic storage?

Hi

The shortest way is

This.storage.set(‘users’,users)

Tom

1 Like

Hi Tom,

this is not working

I am getting my array from Parse Server and save it on

tmp: any [];

and this is the function i run on cloud code

retrieveUsers(){
    if (this.currentUser= Parse.User.current()) {
      Parse.Cloud.run('UserQuery').then(
      res => {
        console.log('user query')
        this.tmp = res;
        console.log(this.tmp);
        this.localdata.setUsers(this.tmp);
        this.users = this.localdata.tmpusers;
        console.log(this.users);

      }
      )
    }
     
   }

and this is my service for local storage

import { Component } from '@angular/core';

export class localData {
    
    setUsers (users){
        window.localStorage.users_data = JSON.stringify(users);
    }
    getUsers(){
       return JSON.parse(window.localStorage.users_data || '[]');
    }

    tmpusers = this.getUsers();
    constructor(){
        this.tmpusers.sort(function(a, b) {
            var nameA = a.username.toUpperCase(); // ignore upper and lowercase
            var nameB = b.username.toUpperCase(); // ignore upper and lowercase
            if (nameA < nameB) {
              return -1;
            }
            if (nameA > nameB) {
              return 1;
            }
                      
            return 0;
          });
    }
    
}  

Hi

You are not using Ionic Storage

So not much I can say until you do so

The code on the doc is straightforward Angular stuff you first need to grasp if you dont get it

Regards

Tom

Well,

I wrote it likes this:

import { Storage } from '@ionic/storage';
import { Injectable, Component } from '@angular/core';
 
@Injectable()
export class Data {

    
    tmpusers = this.getUsers2();
  constructor(public storage: Storage){
     
  }
 
  getUsers2() {
    return this.storage.get('users'); 
  }
 
  setUsers2(users){
    this.storage.set('users', users);
  }
  
}

but i have this error:

Error trying to diff ‘[object Promise]’. Only arrays and iterables are allowed

are you sure that stringify and parse is not needed?

thank you Tom

Hi

Your get returns a promise you need to resolve before you save

So this.getUsers2().then(value=>{this.set etc…)

And then save

Similarly, if the data you het from the server is a promise (which seems to be from the error putput), ypu need to .then it

And the error says you can store arrays…

Regards

Tom

Hi,

I am retrieving from server an object array not a promise.

Also, i first use setusers2() to save the array with ionic storage.

Then i use getusers2() to use this array.

But as i said the problem is that the getusers2() does not return the array cause of the missing json.parse

Your code style looks out of date. I’d recommend you stop using any and var. Instead, learn the basics of Typescript, ES2015, and Promises. That will take a few days. Then the official code for Ionic Storage will make a lot more sense.

1 Like

@AaronSterling thank you for the advice, i really try to understand.

Everything was working with

setUsers (users){
        window.localStorage.users_data = JSON.stringify(users);
    }
    getUsers(){
       return JSON.parse(window.localStorage.users_data || '[]');
    }

and i have replaced with

getUsers2() {
    return this.storage.get('users'); 
  }
 
  setUsers2(users){
    this.storage.set('users', users);
  }

I just cant understand why

Hi

Try to store and get a simple string

If you cant get that to work, even in a simple starter project (or use the Ionic Storage example) then you know you defintely a looking in the wrong direction

Regards

Tom

Hi Tom!

you are right…I make the simple example of git and i get null…

settest(name){
  this.storage.set('name', 'Mr. Ionitron');
  }
  
  gettest(){
  this.storage.get('name').then((name) => {
    console.log('Me: Hey, ' + name + '! You have a very nice name.');
    console.log('You: Thanks! I got it for my birthday.');
  });
}

this name returns null on the console…

any idea??

I managed make it work but not totally…

In the second screen i see that the class of user is retrieved but I cant read the column username. Thats why the list is empty

Any idea?

Hi

working for me allright

check repository https://github.com/Tommertom/storagetest

rgdz

tom

Of course it is working as expected. You have a ready table of items.
I am getting from my Parse Server a response that is not arrray and must be converted to array.

My old code as I have said was working with localstorage.
And by the way i see that localstorage is much more faster than Ionic storage

Hi

Then I suggest you rephrase your question to how to convert a result into array before storing.

Regards

Tom

You are right!

But from the beginning I mentioned that Ionic Storage cannot handle the json response to array.