# Ionic 4 - Correct way of using Local Storage Variables

**URL:** <https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157>\
**Category:** ionic-v3\
**Created:** [May 30, 2019, 9:45pm UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157 "2019-05-30T21:45:18Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![egaldamez](https://avatars.discourse-cdn.com/v4/letter/e/fbc32d/32.png) [@egaldamez](https://forum.ionicframework.com/u/egaldamez)\
**Post date:** [May 30, 2019, 9:45pm UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/1 "2019-05-30T21:45:18Z")

</div>

Hello everybody, im having a little bit of an issue but im not sure if its my inexperience or something else hope someone can help me.  
I have a login form that sends info to my backend and if everything its successful sends me to the main page of the app.  
When the backend responds with error code 200 meaning all was successful, i store data to my local storage to use it along the app usage like Client name.  
This is part of my login function:  
Im using Angular Http module, to make the post into my backend and then i store it on my local storage.

> this.GetService.getData(`LOGINPREM?${urlSearchParams.toString()}`)  
> .subscribe(async data =\> {  
> this.result = JSON.stringify(data); // get data in result variable  
> this.allData = JSON.parse(this.result); // parse json data and pass json string  
> this.dataService.setjsonresult(this.result);  
> // alert(this.dataService.getjsonresult());  
> this.storage.set(‘ID’, this.allData[‘Cliente’]);  
> this.storage.set(‘Nombre’, this.allData[‘Nombre’]);  
> this.storage.set(‘Puntos’, this.allData[‘SaldoPuntos’]);  
> this.storage.set(‘Auth’, 1 );  
> this.GetService.id = this.allData[‘Cliente’];  
> this.GetService.cliente = this.allData[‘Nombre’];  
> this.GetService.puntos = parseInt(this.allData[‘SaldoPuntos’], 0 );  
> this.GetService.isOk = 1;  
> this.authService.login();  
> if (this.allData[‘Error’]== 200) {  
> const toast = await this.toastController.create({  
> message: "Bienvenido " + this.allData[‘Nombre’],  
> position: ‘top’,  
> duration: 2000  
> });  
> toast.present();  
> this.router.navigateByUrl(‘/menu’);  
> return false;  
> } else {  
> const toast = await this.toastController.create({  
> message: "Codigo de Error: " + this.allData[‘Error’] + " Descripcion: " + this.allData[‘Descripcion’] ,  
> position: ‘top’,  
> duration: 2000  
> });  
> toast.present();  
> this.router.navigateByUrl(‘login’);  
> return false;  
> }

When i get to the main page on the ngOnInit, i use the this.storage.get to get all the variables i need like username for example.

This is my ngOnInit.ts

> ngOnInit() {  
> this.isOk = this.newsService.isOk;  
> if (this.isOk) {  
> this.id = this.newsService.id;  
> this.cliente = this.newsService.cliente;  
> this.points = this.newsService.puntos;  
> } else {  
> this.storage.get(‘ID’).then((id) =\> {  
> this.id = id;  
> const urlSearchParams = new URLSearchParams();  
> urlSearchParams.append(‘cliente’, id);  
> this.newsService.getData(`puntos?${urlSearchParams.toString()}`).subscribe(data =\> {  
> this.data = data;  
> if (this.data[‘Error’] === 200) {  
> this.storage.set(‘Puntos’, this.data[‘SaldoPuntos’]);  
> this.points = parseInt(this.data[‘SaldoPuntos’], 0 );  
> }  
> });  
> });  
> this.storage.get(‘Nombre’).then((cliente) =\> {  
> this.cliente = cliente;  
> });  
> }  
> // this.auth();  
> }

I tried to store all the values in a middle service just to make sure i have the information available when getting into the main page.

My problem is when its the **first time** and **ONLY** in the first time my main page shows up, seems like the info is not ready when im trying to use it (this.cliente variable) appears empty when i display it on my html.  
And when im running ionic serve on chrome i check all the information on the local storage and its there already.  
How it looks like the first time i get to the main page:

 ![screen4](https://global.discourse-cdn.com/ionicframework/original/3X/d/2/d22c98a786185616c83ae3d11a0ea223938a5b47.png)

How it SHOULD look like when i get to the main page, and how it looks after refreshing the page or closing and getting the app on again on device:

 ![screen%203](https://global.discourse-cdn.com/ionicframework/original/3X/3/d/3dd28fbe63a4c9654a82f665c2b92dd0728c77d9.png)

So i think theres a problem with how im trying to retrieve all the data.

Should i use: this.storage.ready and inside the then retrieve all the data?  
i.e

> this.storage.ready().then(() =\> {  
> /\*\* set / get some data from the local storage \*/  
> }).catch((error: Error) =\> {  
> console.error(error);  
> return;  
> })

Or i’m doing something else wrong?

Thanks for your time to read my problem, have a great day.

---

<div class="post-metadata">

**Author:** ![Ravinia](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/ravinia/32/118190_2.png) [@Ravinia](https://forum.ionicframework.com/u/Ravinia)\
**Post date:** [June 1, 2019, 7:11pm UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/2 "2019-06-01T19:11:23Z")

</div>

Hi Ernesto,

It’s a bit hard to read with no indentation.

But I think I get the gist. Sure try your storage.ready() solution, sound like it’s in the right direction.

I think it’s good for you to figure this out on your own. Use console.log to print the data at different points in the program and figure out what’s wrong.

Good luck and good job getting this far!

---

<div class="post-metadata">

**Author:** ![egaldamez](https://avatars.discourse-cdn.com/v4/letter/e/fbc32d/32.png) [@egaldamez](https://forum.ionicframework.com/u/egaldamez)\
**Post date:** [June 1, 2019, 8:48pm UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/3 "2019-06-01T20:48:15Z")

</div>

Hello Ravinia, i’ve already tried several things including the storage.ready() but the issue is still there, with other things ive tried i get [object object] too…

---

<div class="post-metadata">

**Author:** ![danieldugger](https://avatars.discourse-cdn.com/v4/letter/d/ad7895/32.png) [@danieldugger](https://forum.ionicframework.com/u/danieldugger)\
**Post date:** [June 2, 2019, 12:27pm UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/4 "2019-06-02T12:27:29Z")

</div>

Are you storing JSON? If so, you’ll need to use JSON.parse to convert the string stored back to an object.

---

<div class="post-metadata">

**Author:** ![egaldamez](https://avatars.discourse-cdn.com/v4/letter/e/fbc32d/32.png) [@egaldamez](https://forum.ionicframework.com/u/egaldamez)\
**Post date:** [June 3, 2019, 4:48am UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/5 "2019-06-03T04:48:48Z")

</div>

Hello Daniel, no im storing a string should i store a json with all the values i need? at the moment i’m storing near 4 different variables as string.

---

<div class="post-metadata">

**Author:** ![egaldamez](https://avatars.discourse-cdn.com/v4/letter/e/fbc32d/32.png) [@egaldamez](https://forum.ionicframework.com/u/egaldamez)\
**Post date:** [June 3, 2019, 9:29pm UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/6 "2019-06-03T21:29:39Z")

</div>

This is a little flowchart of my problem, at the moment when i get to the main page and i try to read the local storage to get the values seems like its not ready and the first time arriving to the page shows the value as empty if i try to console.log it says its undefined the first time, if i refresh the page or go to another page and then i come back all data is ready to work with.

 ![flowchart](https://global.discourse-cdn.com/ionicframework/original/3X/6/f/6fd58dca3289638a1210c6940ed95f1ee65c4485.jpeg)

---

<div class="post-metadata">

**Author:** ![hirenkorat3](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/hirenkorat3/32/128872_2.png) [@hirenkorat3](https://forum.ionicframework.com/u/hirenkorat3)\
**Post date:** [June 4, 2019, 5:01am UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/7 "2019-06-04T05:01:12Z")

</div>

have you fetch your local storage data from your app.component.ts file. ?

few days ago i also had similar issue. so i create method in service and call it in platformready() event in app.component.ts e.g. GetLocalData() in which i fetch all storage data and asign to its service variable.so whenever i want to use localstorage variable i just have to call that method and use that service variable, thats it.

---

<div class="post-metadata">

**Author:** ![egaldamez](https://avatars.discourse-cdn.com/v4/letter/e/fbc32d/32.png) [@egaldamez](https://forum.ionicframework.com/u/egaldamez)\
**Post date:** [June 4, 2019, 5:08am UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/8 "2019-06-04T05:08:31Z")

</div>

Hello, can you provide me some example code please?

---

<div class="post-metadata">

**Author:** ![hirenkorat3](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/hirenkorat3/32/128872_2.png) [@hirenkorat3](https://forum.ionicframework.com/u/hirenkorat3)\
**Post date:** [June 4, 2019, 5:16am UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/9 "2019-06-04T05:16:57Z")

</div>

app.component.ts file

```auto
 constructor(public auth: AuthService){
   this.initializeApp();
}

 initializeApp() {
    this.platform.ready().then(() => {
        this.auth.setUserInfo();
    })
}

```

AuthService service provider

```auto
export class AuthService {
   public currentUser: any = null;

   public setUserInfo() {
    this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
  }
}

```

in every HTML file where you want user Details (you have to create object of AuthService in that’s ts file

```auto
 constructor(public auth: AuthService){}

```

and simply use it in html

```auto
{{auth.currentUser.FirstName + ' ' + auth.currentUser.LastName}}

```

---

<div class="post-metadata">

**Author:** ![hirenkorat3](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/hirenkorat3/32/128872_2.png) [@hirenkorat3](https://forum.ionicframework.com/u/hirenkorat3)\
**Post date:** [June 4, 2019, 5:19am UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/10 "2019-06-04T05:19:51Z")

</div>

here i use localstorage because it is superfast then ionic storage but you also can use ionicstorage same way

---

<div class="post-metadata">

**Author:** ![egaldamez](https://avatars.discourse-cdn.com/v4/letter/e/fbc32d/32.png) [@egaldamez](https://forum.ionicframework.com/u/egaldamez)\
**Post date:** [June 4, 2019, 3:48pm UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/11 "2019-06-04T15:48:52Z")

</div>

> [@hirenkorat3](#):
>
> this.platform.ready()

Sorry for my ignorance, but i have a question does the this.platform.ready() loads up on every route change?

---

<div class="post-metadata">

**Author:** ![egaldamez](https://avatars.discourse-cdn.com/v4/letter/e/fbc32d/32.png) [@egaldamez](https://forum.ionicframework.com/u/egaldamez)\
**Post date:** [June 4, 2019, 8:17pm UTC](https://forum.ionicframework.com/t/ionic-4-correct-way-of-using-local-storage-variables/165157/12 "2019-06-04T20:17:22Z")

</div>

Hello everyone that tried to help i seem to know what my problem is, they way im using local storage its ok BUT when i try to verify if the user has been authenticated before, and use the this.router.navigate or this.router.navigateByUrl its when i get the problem with the local storage getting NULL or undefined.

After i removed that everything is working as intended.

Thanks again to all of you for taking the time answering my question and trying to help.
