The value stored in Ionic Storage will only be visible on the HTML page after a refresh is performed

After updating my Ionic Storage values, they are not showing up on the HTML page until I reload it. I have researched similar issues faced by others, but the solutions I found either do not work or are no longer applicable due to changes in the Ionic version. For example, the Event system in Ionic.

The HTML code displays the Name, and two dates:

<ion-list>
    <div *ngFor="let data of data2">

    <ion-item lines="none">
        <ion-label text-left>
          Fruit Name:
        </ion-label>
        <ion-label text-right>
          {{data.FruitName}}
        </ion-label>
    </ion-item>

    <ion-item lines="none">
      <ion-label text-left>
        Install Date:
      </ion-label>
      <ion-label text-right>
        {{data.installTime}}
      </ion-label>
    </ion-item>

    <ion-item>
      <ion-label text-left>
        Remove Date:
      </ion-label>
      <ion-label text-right>
        {{data.removeTime}}
      </ion-label>
    </ion-item>


    </div>

</ion-list>

.TS file

import {ActivatedRoute} from '@angular/router';
import { Storage } from '@ionic/storage';


export class SummaryComponent implements OnInit {

 //My Variables

 data2;
 _idx;

constructor(
private route: ActivatedRoute,
private storage: Storage,
) { }

ngOnInit() {
this.route.params.subscribe(
  params => {

      /*Update Variables here*/

      this._idx = Temperature.__idx;
      this.storage.ready().then(() => {
        this.storage.get(this._idx).then(data=>{
          //if data exists
          if(data)
            {
             console.log("data read");
             this.data2 = data;
             console.log(data);
            }
            else
            {
              console.log("data is empty");
              this.data2 = [];
            }
        });
      });
  });
}

}

Issue observed when loading the routing page for the first time:

https://i.sstatic.net/eJ4him.png

When changing routing pages and then returning to the original:

https://i.sstatic.net/yu7jDm.png

Answer №1

To implement this in your .ts file, follow these steps:

import {
    ActivatedRoute
} from '@angular/router';
import {
    Storage
} from '@ionic/storage';
import {
    ChangeDetectorRef
} from '@angular/core';


export class SummaryComponent implements OnInit, OnDestroy {

    //Declare Variables
    routeParams;
    data2;
    _idx;

    constructor(
        private route: ActivatedRoute,
        private storage: Storage,
        private changeRef: ChangeDectetorRef
    ) {}

    ngOnInit() {
        this.routePrams = this.route.params.subscribe(params => /** ... do whatever needs to be done with params here **/);

        this._idx = Temperature.__idx;                                                    
        this.storage.get(this._idx).then(data=>{
          //if data exists
          if(data)
            {
             console.log("data read");
             this.data2 = data;
             console.log(data);
            }
            else
            {
              console.log("data is empty");
              this.data2 = [];
            }            
            this.changeRef.detectChanges();
        });
    }

    ngOnDestroy() {
        this.routeParams.unsubscribe();
    }

}

Explanation: Avoid using storage.ready() and ensure you are handling subscriptions properly to prevent memory leaks on the client side. Separate different functionalities for better code organization.

In your template .html, add the following:

<ion-list *ngIf="data2">
    <div *ngFor="let data of data2">

        <ion-item lines="none">
            <ion-label text-left>
                Fruit Name:
            </ion-label>
            <ion-label text-right>
                {{data.FruitName}}
            </ion-label>
        </ion-item>

        <ion-item lines="none">
            <ion-label text-left>
                Install Date:
            </ion-label>
            <ion-label text-right>
                {{data.installTime}}
            </ion-label>
        </ion-item>

        <ion-item>
            <ion-label text-left>
                Remove Date:
            </ion-label>
            <ion-label text-right>
                {{data.removeTime}}
            </ion-label>
        </ion-item>


    </div>

</ion-list>

Explanation: Since the storage result is a promise-like object, you need to wait for it to resolve before displaying the data on the template. Check the status of the variable data2 to handle the asynchronous nature of the storage call and ensure proper timing of data retrieval.

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

What are the best practices for implementing MapLabel in an Angular project?

I need help displaying text on top of multiple polygons on a map. I've heard that Map Label can help with this, but I'm having trouble implementing it and can't find any NPM resources. Here is the Stack Blitz URL for reference: https://stac ...

Steps for exporting various elements from a .vue file

In my Vue project, I am incorporating TypeScript along with Vue. There is a specific scenario where I need to export multiple items from my .vue file. Here's an example of what I want to achieve: // FooBar.vue <template> ... </template& ...

Steps for attaching attributes to a displayed element in TileVectorLayer

As seen in the code below, I am creating a VectorTileLayer where the VectorTileSource is showing MVT geometry retrieved from a webservice specified in the url attribute. The database table includes columns as follows. The webservice will be called for each ...

Is it possible to alter the name of a slot before displaying the element in the shadowDOM, depending on the slot utilized in the DOM?

In my project, I am working on implementing different features for both desktop and mobile devices. Some of these features can be replaced by slots. My goal is to have a slot that can be either replaced by a desktop slot called poster-foreground, or a mobi ...

Angular 6 - Deleting the node_module package to streamline local project modifications

After reviewing our options, we have decided to implement ng2-smart-table for the table grid in our current project. However, we've encountered some limitations with its functionality that do not fully meet our project requirements. As a result, we a ...

Unable to invoke the AppComponent function within ngOnInit due to error message: "Object does not have the specified property or method"

I'm a novice in Angular and I am attempting to invoke my function setCenter2() from the AppComponent class within the ngOnInit function of the same class. Is this achievable? Whenever I try to call my function by clicking on the map (using OpenStreetM ...

Having trouble customizing the toolbar on ngx-quill? Quill seems to be having trouble importing modules

UPDATE: I jumped ship when I discovered that PrimeNg had a quill implementation, and since I was already using PrimeNg, I switched over. Initially had some issues, but upgrading to angular 7 and ngrx 7 beta resolved them. https://www.primefaces.org/primeng ...

Instructions on how to dynamically show specific text within a reusable component by utilizing React and JavaScript

My goal is to conditionally display text in a reusable component using React and JavaScript. I have a Bar component that I use in multiple other components. In one particular ParentComponent, the requirement is to show limit/total instead of percentage va ...

Manage scss styles consistently across Angular projects with this Angular library designed to

In an effort to streamline my development process, I am looking to consolidate my commonly used styles that are defined in my Angular library. My goal is to easily leverage mixins, functions, variables, and more from my library in future projects. Previou ...

Issue with Material UI Table not refreshing correctly after new data is added

Currently, I am utilizing a Material-UI table to display information fetched from an API. There's a form available for adding new entries; however, the problem arises when a new entry is added - the table fails to update or re-render accordingly. For ...

Is there a way for me to access the names of the controls in my form directly from the .html file?

I have a list where I am storing the names of my form controls. In order to validate these form controls, I need to combine their names with my code in the HTML file. How can I achieve this? Below is my code: .ts file this.form = this.formBuilder.group({ ...

WebStorm highlights user-defined Jasmine matchers as mistakes and displays `TypeScript error TS2339: Property 'matcher' does not exist on type 'ArrayLikeMatchers '`

I am currently working on testing a hybrid Angular and Angular.js app using Karma / Jasmine. The previous code utilized custom matchers which worked flawlessly, and these same matchers are being used in the new TypeScript code. Strangely, although the Type ...

Challenges with Type Aliases when Using Typescript with MaterialUI Icons

I am searching for a way to dynamically incorporate Material UI icons into my code based on specific strings found in a configuration file. I have come across an approach that seems promising: https://medium.com/@Carmichaelize/dynamic-tag-names-in-react-a ...

How can you retrieve data in Angular through an API call using the get method?

How can I make an API call to retrieve data from this URL, , using a GET method without passing any parameters in my Angular application? What is the code snippet required for this, and do I need to import any specific libraries or declare specific variabl ...

Testing TypeScript functionality within the Eclipse environment with unit tests

Is there a method to test TypeScript code on the Eclipse platform? I'm searching for something similar to JUnit, but most of the tools I've come across are geared towards Visual Studio. ...

In Angular, set the default value of the first item in the list to be highlighted when the page loads

In my project, there are two key components: 1)contact and 2)display. The contact component is responsible for displaying a list of contacts as shown in the image below: https://i.sstatic.net/SnXFZ.png Next to the contact component, I have placed anothe ...

An issue has arisen with loading chunks in Ionic 5/Angular, possibly due to an un

I am currently working on enhancing the offline capabilities of my Ionic 5 app. To achieve this, I have implemented a strategy where data is stored in SQLite while the app is connected, and then retrieved from SQLite when offline instead of making HTTP req ...

What is the method to define a function that strictly accepts a value of type T only if IsSomething<T> evaluates to true?

In my system, there is a complex generic type called IsUnique<T> that evaluates to either true or false based on the input type T: type IsUnique<T> = (/* ... */) ? true : false; Now I am looking to develop a function that takes an unique value ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

Delay the Ngrx effect by 2 seconds before initiating the redirect

I have an ngrx effect that involves calling an HTTP method and then waiting for 2 seconds before redirecting to another page. However, the current behavior is that it redirects immediately without waiting. confirmRegistration$ = createEffect(() => { ...