How to get data stored at the very first start of the application?


#1

Hello,

I’ve got a problem with the storage. I set storage when I push a button to store some variables, so it’s possible to get those variables after refreshing and click on a button “get” (I follow some tutorials online).

The thing is that I don’t want to click a button to get the data stored but instead I’d like to get those data automatically at the beginning of the application so, I put the “get function” in the constructor.

The problem is when I don’t set any data with my button, when I get the data, it returns null or nothing or strange values because, of course I didn’t set anything.

I don’t know how to get data at the beginning automatically without a button to set and get. Can you help me ?

Thanks a lot.


#2

Hi

Can you post your get method when getting data from storage using a service you want to return a promise in the service then in your page or component do do this

this.dataService().getData().then(data=>{
do something with your data
});
Without this you may have some issues with getting data from storage being an async method


#3

I have no problem to get my data stored but the problem is when I start the app for the first start with no data stored. If I try to get data, I have errors and the progam can’t work.

On one page I have this :

getData() {
    this.storage.get('myData').then((data0) => {
      this.data = data0[0];
      this.items = data0[1];
      this.totalActionsArray["home"] = data0[2];
      this.totalPointsArray["home"] = data0[3];
      this.events.publish('hello', this.name);
    });
  }

And this to set :

never(SlidingItem, item) {
    item.points = 0;
    item.action = 0;
    item.label = item.label0,
      this.totalActionsArray["home"] = this.totalActions();
    this.totalPointsArray["home"] = this.totalPoints();
    this.storage.set('myData', [this.data, this.items, this.totalActionsArray["home"], this.totalPointsArray["home"]]);
    this.storage.set('firstStart', 'false');
    this.events.publish('hello', this.name);
    SlidingItem.close();
  }

The whole page look like this :

import { Component } from '@angular/core';
import { NavController, App, MenuController, Events } from 'ionic-angular';
import { Storage } from '@ionic/storage';

import { Action1 } from '../action1/action1';
import { Information } from '../information/information';

import { MyService } from '../../app/my.service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class Home {

  //total = this.totalActions();
  items = [];
  data = [];
  totalActionsArray = {};
  totalPointsArray = {};
  btnName: any = 'Edit';
  flag: any = false;
  name: string;
  hideElement: boolean = false;
  firstStart: boolean = true;

  selectContext = {
    title: 'Context',
  };

  selectCategory = {
    title: 'Category',
  };

  constructor(app: App, menu: MenuController, public navCtrl: NavController, private myservice: MyService, public events: Events, public storage: Storage) {

    this.data = myservice.getItemsHome();
    this.items = myservice.getItemsHome();
    this.totalActionsArray = myservice.getTotalActions();
    this.totalPointsArray = myservice.getTotalPoints();
  }

  getData() {
    this.storage.get('myData').then((data0) => {
      this.data = data0[0];
      this.items = data0[1];
      this.totalActionsArray["home"] = data0[2];
      this.totalPointsArray["home"] = data0[3];
      this.events.publish('hello', this.name);
    });
  }

  onContextChange(value): void {
    if (value == 'all') {
      this.items = this.data;
    }
    else {
      this.items = this.data;
      this.items = this.items.filter(item => item.context === value);
    }
  }

  onCategoryChange(value): void {
    if (value == 'all') {
      this.items = this.data;
    }
    else {
      this.items = this.data;
      this.items = this.items.filter(item => item.category === value);
    }
  }

  reorderItems(indexes) {
    let element = this.items[indexes.from];
    this.items.splice(indexes.from, 1);
    this.items.splice(indexes.to, 0, element);
  };

  actionBtn() {
    if (this.btnName == 'Edit') {
      this.btnName = 'Done';
      this.flag = true;
    }
    else {
      this.btnName = 'Edit';
      this.flag = false;
    }
  };

  goToInformation() {
    this.navCtrl.push(Information);
  }


  goTo(item) {
    if (item.link == "Action1") {
      this.navCtrl.push(Action1);
    }
  }


  never(SlidingItem, item) {
    item.points = 0;
    item.action = 0;
    item.label = item.label0,
      this.totalActionsArray["home"] = this.totalActions();
    this.totalPointsArray["home"] = this.totalPoints();
    this.storage.set('myData', [this.data, this.items, this.totalActionsArray["home"], this.totalPointsArray["home"]]);
    this.storage.set('firstStart', 'false');
    this.events.publish('hello', this.name);
    SlidingItem.close();
  }

  rarely(SlidingItem, item) {
    item.points = 25;
    item.action = 1;
    item.label = item.label25,
      this.totalActionsArray["home"] = this.totalActions();
    this.totalPointsArray["home"] = this.totalPoints();
    this.storage.set('myData', [this.data, this.items, this.totalActionsArray["home"], this.totalPointsArray["home"]]);
    this.storage.set('firstStart', 'false');
    this.events.publish('hello', this.name);
    SlidingItem.close();
  }

  sometimes(SlidingItem, item) {
    item.points = 50;
    item.action = 1;
    item.label = item.label50,
      this.totalActionsArray["home"] = this.totalActions();
    this.totalPointsArray["home"] = this.totalPoints();
    this.storage.set('myData', [this.data, this.items, this.totalActionsArray["home"], this.totalPointsArray["home"]]);
    this.storage.set('firstStart', 'false');
    this.events.publish('hello', this.name);
    SlidingItem.close();
  }

  often(SlidingItem, item) {
    item.points = 75;
    item.action = 1;
    item.label = item.label75,
      this.totalActionsArray["home"] = this.totalActions();
    this.totalPointsArray["home"] = this.totalPoints();
    this.storage.set('myData', [this.data, this.items, this.totalActionsArray["home"], this.totalPointsArray["home"]]);
    this.storage.set('firstStart', 'false');
    this.events.publish('hello', this.name);
    SlidingItem.close();;
  }

  always(SlidingItem, item) {
    item.points = 100;
    item.action = 1;
    item.label = item.label100,
      this.totalActionsArray["home"] = this.totalActions();
    this.totalPointsArray["home"] = this.totalPoints();
    this.storage.set('myData', [this.data, this.items, this.totalActionsArray["home"], this.totalPointsArray["home"]]);
    this.storage.set('firstStart', 'false');
    this.events.publish('hello', this.name);
    SlidingItem.close();
  }

  plural() {
    var total = this.totalActions()
    if (total > 1) {
      return "actions"
    }
    else {
      return "action"
    }
  }

  totalPoints() {
    var total = 0;
    for (var i = 0; i < this.data.length; i++) {
      var data = this.data[i];
      total += data.points;
    }
    if (total > 1) {
      return Math.floor(total / this.data.length); // + " points";
    }
    else {
      return Math.floor(total / this.data.length); // + " point";
    }
  }

  totalActions() {
    ;
    var total = 0;
    for (var i = 0; i < this.data.length; i++) {
      var data = this.data[i];
      total += data.action;
    }
    if (total > 1) {
      return total; // + " actions";
    }
    else {
      return total; // + " action";
    }

  };

}


#4

You seem to be storing everything in an array. That’s really fragile and hard to read. Store an object instead:

export interface Action {
// no idea what goes in here
}

export interface Item {
// no idea what goes in here
}

export interface AppState {
  items: Item[];
  actions: Action[];
  points: number[]; 
}

saveAppState(state: AppState): void {
  this.storage.set('appState', state);
}

restoreAppState(): Promise<AppState> {
  return this.storage.get('appState');
}

As for the issue for what happens if there isn’t anything stored, you have to be prepared for restoreAppState to return null or reject, and populate things with appropriate initial defaults.


#5

Ok, I’ll try to store an object insteaf but I still don’t understand the method to initialize defauts. How to do it ? I think it’s a lack of experience for me in coding.
I tried something with a boolean to store if it’s the first start but same problem, I can’t get a boolean before I set it so I turn around.
I tried to make a condition, if ‘null’, intialize but it’s not always null, sometimes it’s just weird value so I don’t know how to do it.


#6

No way I can know what your defaults would be, but the basic idea is:

restoreAppState(): Promise<AppState> {
  return this.storage.get('appState').then((state) => {
    if (!state) {
      // storage had nothing for us
      state = {
        items: [{name: 'lamp'}, {name: 'elvish sword'}],
        actions: [{name: 'examine'}, {name: 'drop'}],
        points: [],
      };
    }
    return state;
  });
}

#7

this.service.getCampaigns()
.subscribe((items) => {

  this.funds = items;
    
    this.session = JSON.parse(sessionStorage.getItem('funds'));
      console.log(this.session)
    if (this.session !== null && this.session!== undefined && this.session.length === this.funds.length) <---- this line is important to check if not null and not undefined and finally compare from what comes from the provider service.

Happy day coding


#8

I thought sessionStorage didn’t work on device.


#9

Thanks, that’s what I’m looking for. I wanted to do that but I didn’t manage to ! Thanks for all your help by the way, my first app is almost done and you help a lot !