Ionic 4 - Correct way of using Local Storage Variables

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:

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:

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.

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!

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…

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

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.

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.

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.

Hello, can you provide me some example code please?

app.component.ts file

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

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

AuthService service provider

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

 constructor(public auth: AuthService){}

and simply use it in html

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

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

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

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.