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

**URL:** <https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810>\
**Category:** ionic-v3\
**Created:** [May 3, 2017, 8:15pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810 "2017-05-03T20:15:01Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![Julien\_Lu](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/julien_lu/32/108909_2.png) [@Julien\_Lu](https://forum.ionicframework.com/u/Julien_Lu)\
**Post date:** [May 3, 2017, 8:15pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/1 "2017-05-03T20:15:01Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Dachu](https://avatars.discourse-cdn.com/v4/letter/d/f07891/32.png) [@Dachu](https://forum.ionicframework.com/u/Dachu)\
**Post date:** [May 3, 2017, 8:28pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/2 "2017-05-03T20:28:30Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Julien\_Lu](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/julien_lu/32/108909_2.png) [@Julien\_Lu](https://forum.ionicframework.com/u/Julien_Lu)\
**Post date:** [May 3, 2017, 8:36pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/3 "2017-05-03T20:36:44Z")

</div>

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 :

```auto
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 :

```auto
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 :

```auto
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";
    }

  };

}

```

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 3, 2017, 8:42pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/4 "2017-05-03T20:42:32Z")

</div>

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

```auto
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.

---

<div class="post-metadata">

**Author:** ![Julien\_Lu](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/julien_lu/32/108909_2.png) [@Julien\_Lu](https://forum.ionicframework.com/u/Julien_Lu)\
**Post date:** [May 3, 2017, 9:16pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/5 "2017-05-03T21:16:42Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 3, 2017, 9:27pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/6 "2017-05-03T21:27:02Z")

</div>

> [@Julien\_Lu](#):
>
> I still don’t understand the method to initialize defauts.

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

```auto
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;
  });
}

```

---

<div class="post-metadata">

**Author:** ![hainako](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/hainako/32/112930_2.png) [@hainako](https://forum.ionicframework.com/u/hainako)\
**Post date:** [May 3, 2017, 10:32pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/7 "2017-05-03T22:32:31Z")

</div>

`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

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [May 3, 2017, 10:48pm UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/8 "2017-05-03T22:48:08Z")

</div>

I thought `sessionStorage` didn’t work on device.

---

<div class="post-metadata">

**Author:** ![Julien\_Lu](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/julien_lu/32/108909_2.png) [@Julien\_Lu](https://forum.ionicframework.com/u/Julien_Lu)\
**Post date:** [May 4, 2017, 12:13am UTC](https://forum.ionicframework.com/t/how-to-get-data-stored-at-the-very-first-start-of-the-application/88810/9 "2017-05-04T00:13:17Z")

</div>

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 !
