Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page.

I'm starting to think that I may have misunderstood something. Is there a way to make a synchronized call to Ionic Storage instead of an asynchronous one? My goal is to check if a user profile is stored on the device, and if it's not, redirect back to the login screen. Unfortunately, it seems like the call to Ionic Storage takes too long and isn't resolved by the time the page loads.

Here is part of my code:

private user:User;
constructor(private storage: Storage) {   
    storage.get('user').then(data => {
      this.user = data;
    });
  }

And here is how I am trying to display the data in my HTML template:

<ion-content padding>
  <div>
    <p>Welcome <b>{{user.name}}</b></p>    
  </div>
</ion-content>

But, as I mentioned earlier, this approach gives me an error indicating that user.name is undefined. Using the ngIf directive to wait for the promise to resolve solves the issue, but I feel like I might be missing something fundamental here.

<ion-content padding>
  <div *ngIf="user">
    <p>Welcome <b>{{user.name}}</b></p>    
  </div>
</ion-content>

So, my question is: How can I ensure that the data fetched from Ionic Storage is available when the page is loaded or entered?

Answer №1

Perhaps there was a misunderstanding of the concept, but is it feasible to execute a synchronized call to Ionic storage instead of an asynchronous one?

Given that this operation is asynchronous, it seems unlikely that you can achieve it in a synchronous manner. Nevertheless, your approach of using *ngIf="user" is effective. You could also consider incorporating something like

  <div *ngIf="!user">
     //Display a spinner or loading bar
  </div>

Answer №2

There is a delay in retrieving the user from storage, hence the wait time.

To prevent errors, consider this alternative instead of using *ng-if:

private user:User = new User(); // Initialize the user property

constructor(private storage: Storage) {   
    storage.get('user').then(data => {
        this.user = Object.assign(new User, data);
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have a specific resolution in mind where I want to run jQuery code during window scrolling

I have a jQuery code that I want to run only when the resolution is greater than 950px. If not, I risk losing the responsive logo. My goal is to create a navigation bar similar to the one on the Lenovo homepage. $(document).ready(function(){ //left ...

What is the method for obtaining the number of weeks since the epoch? Is it possible to

Currently, I am setting up a DynamoDb store for weekly reporting. My idea is to use the week number since 1970 as a unique identifier for each report record, similar to epoch milliseconds. Here are some questions I have: How can I determine the current w ...

What methods can I use to combine AngularJS, React, and Redux together?

As I develop an application with angular and redux using ngRedux, I am considering switching to react for better performance. Since the application is extensive, rebuilding it from scratch is not feasible. My plan is to utilize angularJS routing (angular-u ...

Any modifications made to a copied object will result in changes to the original object

The original object is being affected when changes are made to the cloned object. const original = { "appList": [{ "appId": "app-1", "serviceList": [{ "service": "servic ...

Implement an autocomplete feature for input tags that are added dynamically

I am currently building an autocomplete feature for an input field using the code snippet below: $('.query').autocomplete({ serviceUrl:'http://localhost/main/finder.php', minChars:2, delimiter: /(,|;)\s*/, // regex or ...

A guide to presenting array data retrieved from an Ajax call within HTML using Laravel 4.1

I have an AJAX call to a controller that returns array data to my view. I want to display this array data in HTML upon clicking, but I'm not sure how to do it yet. Here's what I have so far: AJAX Call: request = $.ajax({ url: "/fans/ ...

Setting up React Native on a Mac M1 device

I am currently setting up React Native on my MacBook M1 Despite having installed npm, JDK, Node, Rosetta, CocoaPod, VSCode, Android Studio, Xcode and more, when I try to run the command (npm start), the directories for iOS and Android are not present. The ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

No output is displayed in the absence of errors. The program is functioning correctly

app.js angular.module('app', ['ionic', 'ui.router']) .config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){ $urlRouterProvider.otherwise('/'); $sta ...

What is the best way to programmatically activate a selectbox click within a function's scope?

I am currently developing a mobile app with phonegap, jQuery Mobile, and AngularJS. I am trying to activate a click event once I have clicked on another icon. To achieve this, I am calling a scope function where I have attempted using $('#id').c ...

The functionality of the web application is not supported in Multi-Device-Hybrid-Apps format

I am encountering an issue with my app that functions perfectly as a typical web app, but fails to work properly when converted into a Multi-Device-Hybrid-App format. The problematic sections are indicated in a screenshot of the app. Below is my complete c ...

Is there a restriction on the number of routes available from Google Maps Directions Service?

Utilizing the Google Maps Directions API, I am able to calculate the distance between the current user's location and various stores. Everything functions properly until I exceed 10 store locations, at which point the API ceases to operate due to its ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...

Can CSS be used to communicate to JavaScript which media queries are currently in effect?

Is there a way for Javascript to detect when a specific CSS media query is active without repeating the conditions of the media query in Javascript? Perhaps something similar to an HTML data attribute, but for CSS. For example: CSS @media (min-width: 94 ...

Transform a PHP array into a JavaScript array with UTF-8 encoding

I am currently facing an issue with a products table that contains foreign characters. My goal is to utilize a PHP array in JavaScript to filter a dropdown box as the user types. Everything seems to be working fine except when encountering foreign characte ...

implement a new directive in AngularJS that references another directive in HTML

Check out the Fiddle here Upon button click, a modal window appears. Inside this modal, there is a <template-placeholder></template-placeholder>. When the button is clicked, an if-check is performed to ensure it's the correct button. If ...

Guide to making a slider menu using html, css, and javascript

Just dipping my toes into the world of web development. I'm intrigued by the idea of creating a "slider menu" where users can view and select options by clicking on next or previous buttons (see example image below). While I've got some basic HTM ...

What steps can be taken to stop 'type-hacking'?

Imagine owning a popular social media platform and wanting to integrate an iframe for user signups through third-party sites, similar to Facebook's 'like this' iframes. However, you are concerned about the security risks associated with ifra ...

Ways to organize an array based on various characteristics

I am seeking assistance regarding grouping in Javascript. Below is an array where each item has either is_sweet, is_spicy, or is_bitter set to true: const foodsData = [{ name: 'mie aceh', is_sweet: false, is_spicy: true, ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...