Could Not Assign Data Fetched From Native Storage To Variable

Hello Friends,

One of my ionic project, am using Native Storage To Store Customer ID and Fetching It Where It Needs, by the way i have fetched from native storage successfully, and assigned to local variable and printed it also(in console). but while calling API the variable value is send as undefined. i could not track this problem long time, meanwhile this problem occurred occasionally. sometimes it have value and sometimes it happen, i have no idea about it, please help me to resolve this. Thanks in Advance.

Sample Code Structure:


import { NativeStorage } from ‘@ionic-native/native-storage/ngx’;

@Component({

})

export class CheckoutPage implements OnInit {

customer_id: any;

constructor(private nstore : NativeStorage) {
}

ngOnInit() {

this.getCustomerId(); 
confirmOrder();

}

getCustomerId(){

//get customer id from local storage

this.nstore.getItem('PROJECT_USER').then((user)=>{

  console.log("Fetching Success");

  console.log(user);

  console.log("User ID"+user.ID);

  this.customer_id=user.ID;

  console.log("Customer ID"+this.customer_id);

},(error)=>{

  console.log("Error Occure on Fetching Native Storage");

}); 

}

confirmOrder()
{

this.ds.confirmOrder(this.customer_id).subscribe((res)=>{      
 //here the customer id is undefined sometimes ,so i could not do futher process
 ....
},(err)=>{      
  ...

})

}

}

It may not seem related at first glance, but try reading through this thread, as I think you are in a very similar situation.

You are relying on side-effects of getCustomerId that you have no way of predicting the timing of. I would instead rearchitect getCustomerId so that it returns Promise<User> (and, incidentally, I would move that method totally out of the page and into a service provider). Also please consider adopting customary JavaScript naming conventions, which would make customer_id customerId instead. Give it a proper type, too. Every use of any is a missed opportunity to write more robust, self-documenting, and mantainable code.

thank you, i will try this.