Navigating the realm of Ionic Storage: mastering simplicity within the realm of Promises

Using Ionic Storage has been quite challenging for me as it returns a Promise, which I find to be impractical.

I am trying to retrieve a value from Storage and based on its boolean value, perform certain actions.

In my old Angular 1 code, I had the following:

$scope.isUser = UserService.getUser() ? true : false;
$scope.isUserTemp = storageService.get("userTemp") ? true : false;
$scope.data.showLoginClose = ($scope.isUser || $scope.isUserTemp || !$rootScope.isMobile );

Below is my new TypeScript implementation:

 let isUser: boolean;
    let isUserTemp: boolean;
    this.storage.ready().then(() => {
        this.storage.get('userTemp').then((val) => {
            isUserTemp = true ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
        .catch( (e) => {
            isUserTemp = false ;
            isUser = UserService.getUser() ? true : false;
            this.data.showLoginClose = (isUser || userTemp || !this.isCordova.f() );
        })
    });

It seems like the new code is much longer compared to the old one, with 14 lines instead of just 3.

Could someone assist me in creating a cleaner Promise-based solution in Angular2 / TypeScript that covers all scenarios (e.g. when isUser is true, userTemp is true; when isUser is false, userTemp is true; etc.)?

Answer №1

According to @VinceOPS, a revised logic has been implemented due to the use of Ionic Storage which is built on localForage. It should be noted that even if the desired variable is not found in Storage, the .then() function will still execute and in such cases, the value of ̀val will be null.


    let self = this;
    this.storage.ready().then(() => {
        return this.storage.get('userTemp');
    })
    .then(retrieved => updateLoginClose(retrieved))
    .catch(err => console.error('ERROR: Failed to retrieve data from Storage. Error:', err));

    function updateLoginClose(retrieved) {
       let isUserTemp:boolean;
       if (retrieved !== null) {
          isUserTemp = true;
       } else {
          isUserTemp = false;
       }
       self.data.showLoginClose = isUserTemp || self.UserService.getUser() || !self.isCordova.f();
    }

Answer №2

By eliminating unnecessary variables like isUserTemp (which is simply assigned either true or false, making it redundant in conditions) and isUser (which relies solely on UserService.getUser()), here is the refined code:

this.storage.ready().then(() => {
    return this.storage.get('userTemp');
}).then((val) => {
    this.data.showLoginClose = (UserService.getUser() || !this.isCordova.f());
}).catch((e) => {
    this.data.showLoginClose = (UserService.getUser() || !this.isCordova.f());
});

I sense a flaw in the logic. After some restructuring, you might end up with something like this:

function updateLoginClose(isUserTemp: boolean) {
    this.data.showLoginClose = isUserTemp || UserService.getUser() || !this.isCordova.f();
}

this.storage.ready().then(() => {
    return this.storage.get('userTemp');
})
.then(val => updateLoginClose(!!val))
.catch(() => updateLoginClose(false));

Remember to handle variables val and e appropriately, or exclude them if not needed.

EDIT - Consider incorporating val.

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

Error TS2322: Cannot assign type 'Foo | Bar' to type 'Foo & Bar'

I am attempting to save an item in an object using the object key as the discriminator for the type. Refer to the edit below. Below is a simple example: type Foo = { id: 'foo' } type Bar = { id: 'bar' } type Container = { foo ...

Creating a Node API that can patiently listen for external data

My current project involves building a server that fetches data from an external API and returns it to the endpoint localhost:3000/v1/api/. However, I'm facing a challenge where the data retrieval process takes approximately 2 seconds, leading to empt ...

A unique approach to handling ngdisabled for fields that are required only

Starting off with a requirement to disable the submit button when a required field is left empty. <form name="form"> <input type="text" placeholder="First Name" data-ng-model="model.firstName" name="FirstName" ng-required="true" /><br/> ...

Issue with Angular form not triggering ng-submit functionI am facing a problem where

Issue with angular submission: I've been trying to implement a simple submission feature using angular, but the $scope.account_create.submit function isn't getting called upon submission. I have added the name attribute to the form and ensured th ...

Exploring the attributes used in AngularJS directives

I have been exploring AngularJS and noticed that it introduces unique attributes that do not follow the standard HTML attribute format, such as: <html ng-app> or <body ng-controller="PhoneListCtrl"> Where do these ng-* attributes originate ...

Choosing a personalized component using document selector

Currently, I am working on an application using Stenciljs and have created a custom element like this: <custom-alert alertType="warning" alertId="warningMessage" hide>Be warned</custom-alert> The challenge arises when attem ...

AngularJS: Issue with watching arrays and deep $watch functionality

I'm having trouble using the $watch function in AngularJS with an array of boolean values. I want to display a message when there's a change in the array, but it's not working as expected. Check out this code example where the array values ...

Toggle button visibility in AngularJS based on checkbox selection

I'm currently utilizing ng-table to construct my table. I have a button positioned at the top of the table that is initially disabled. My goal is to enable this button only when any of the checkboxes are selected. The button should automatically disab ...

Guide to dynamically loading select options in AngularJS from a JSON file

Is there a way in AngularJS to populate select options from a JSON file? I am trying to figure out how to populate the dropdown with the following: todos.products.[DynamicProductName].attributes.Location Given that there are multiple product names under ...

I encountered an issue where I did not receive a response when utilizing res.write() within the fetch function

Currently, I am utilizing the <res.write()> method in nodejs at https://nodejs.org/api/http.html#responsewritechunk-encoding-callback. In addition to this, I am also implementing the fetch function which can be found at https://developer.mozilla.org/ ...

When incorporating libp2p into the main.ts file of an Electron application, the error "self is not defined" may occur

When importing libp2p in main.ts of an electron app like this: const Libp2p = require('libp2p'); An error is triggered: A JavaScript error occurred in the main process Uncaught Exception: ReferenceError: self is not defined at Object../node_ ...

Maximizing the timeout efficiency in Firebase Cloud Functions

In my project, I have a function that triggers the sending of emails every time a new element is added to the database. The function grabs email addresses for specific users and sends out emails accordingly. Now, I'm running this function every time ...

Removing Embedded Json Element from a Collection in AngularJS HTML

In my JSON Collection, I want to display the Email ID that is marked as IsPreffered = TRUE using AngularJS HTML without using JavaScript. This is my JSON Collection: { "user" : [ { "Name" : "B. Balamanigandan", "Email": [ ...

Using AngularJS with Spring MVC and @RequestParam

As a newcomer to AngularJS, I have a Spring controller that retrieves an object from the database based on its id. I want to pass this id using @RequestParam in AngularJS. However, when attempting to do so, I encountered the following error message: "Error ...

Next.js focuses solely on rendering markup and does not run any custom code

I am in the process of creating a website, where currently the only functionality available is to change themes by selecting an option from a dropdown menu (the theme is an attribute that uses CSS variables). Everything was functioning properly, however t ...

Generating interactive HTML content using a JSON file with AngularJS

Currently, I am working on a project where I have a nested JSON object within AngularJS. In order to create a menu from this JSON using the Bootstrap navbar, I need assistance with parsing the highly nested structure and generating dynamic HTML code to d ...

Prevent the occurrence of endless looping in serializer (angularjs) by avoiding infinite recursion

Currently, I am working on a RESTful application that involves @OneToMany relationships. The entities in question are Team and Player (where one Team can have many Players, and each Player belongs to only one Team). To prevent infinite recursion, I decid ...

Restricting data list values in AngularJS

Currently, I am facing a performance issue while trying to display approximately 2000 values retrieved through an API call using DataList in AngularJS. The page becomes extremely slow due to the large number of items being rendered. Is there a way to optim ...

Creating text buttons in Angular: A step-by-step guide

I am looking to design three unique buttons that will reveal specific information when clicked. I have uploaded an image as a reference for how they could be displayed. Each button, when clicked on "learn more", should display the corresponding descripti ...

The current state of this scenario is not clearly defined within the parent class

Here is the scenario that caught my attention: abstract class Base { public _obj = { name: 'Test' } print1() { console.log(this._obj) } print2() { console.log(this) } } class Child extends Base { print2( ...