At runtime, the array inexplicably becomes null

Having recently ventured into the world of Ionic framework development, I have encountered a puzzling issue. At runtime, an array inexplicably gets nulled and I am struggling to pinpoint the root cause.

    export interface Days
{
  name:string;
}

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage
{
  days = [] as Days[];
  constructor(public navCtrl: NavController, public alertCtrl: AlertController, public navParams: NavParams)
  {

  }

  presentDayDialog(): void
  {
    let alert = this.alertCtrl.create({
      title: 'Add new day',
      message: 'Enter a name for the new day',
      inputs: [
        {
          name: 'day',
          placeholder: 'Day'
        },
      ],
      buttons: [
        {
          text: 'Cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Save',
          handler: data => {
            this.addDays(data.day);
          }
        }
      ]
    });
    alert.present();
  }

  addDays(rname): void
  {
    this.days.push({name: rname});
  }

  itemTapped(Days)
  {
    this.navCtrl.push(RoutinePage, {
      pageName: Days.name
    });
    console.log("The page name was "+Days.name);
  }
}

export interface Routine
{
  name:string;
  weight: number;
  reps: number;
}

@Component({
  selector: 'page-routine',
  templateUrl: 'routine.html'
})

export class RoutinePage
{
  routines = [] as Routine[];
  public pageName;

  constructor(public navCtrl: NavController, public toastCtrl: ToastController, public alertCtrl: AlertController, public platform: Platform, public storage: Storage, public navParams: NavParams)
  {
    console.log('PRE CONSTRUCTOR ' + this.routines);

    this.pageName = navParams.get("pageName");
    this.getRoutines();
    console.log('POST CONSTRUCTOR ' + this.routines);
  }

  //Sets the routines to storage
  setRoutines()
  {
    console.log('ROUTINES ARRAY before setRoutine() '+ this.routines );
    this.storage.set(this.pageName, this.routines );
    console.log('ROUTINES ARRAY after setRoutine() '+ this.routines );
  }

  //Gets the routines from storage, this gets executed at the construction of this page so it isn't empty at the start
  getRoutines()
  {
    console.log('ROUTINES ARRAY before getRoutine() '+ this.routines );
    this.routines = [{name: 'Jogger', weight: 0, reps: 0}];
    this.storage.get(this.pageName).then((data) => {
      this.routines = data;
    });
    console.log('ROUTINES ARRAY after getRoutine() '+ this.routines );
  }

  //Adds a new routine and saves it to storage
  addRoutine(rname): void
  {
    console.log('ROUTINES ARRAY before addRoutine() '+ this.routines );
    this.routines.push({name: rname, weight: 0, reps: 0});
    console.log('ROUTINES ARRAY after addRoutine() ' + this.routines);
    this.setRoutines();
  }

  //Presents the dialog for adding a new routine on FAB-button-press, calls addRoutine function
  presentRoutineDialog(): void
  {
    let alert = this.alertCtrl.create({
      title: 'Add new routine',
      message: 'Enter a name for the new routine',
      inputs: [
        {
          name: 'routine',
          placeholder: 'Routine'
        },
      ],
      buttons: [
        {
          text: 'Cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Save',
          handler: data => {
            console.log('ROUTINES ARRAY AFTER SAVE BUTTON PRESS:' +this.routines);
            this.addRoutine(data.routine);
          }
        }
      ]
    });
    console.log('ARRAY BEFORE ALERT: ' + this.routines);
    alert.present();
    console.log('ARRAY AFTER ALERT: ' + this.routines);    
  }  
}

My approach involves adding items (Days) to a list on the "first" page. When clicking on an item, a second page opens with the Day's name becoming the name of the page. This name acts as the key for storing the array in the device's storage. Each page has its own storage to display information upon construction.

THE ISSUE: For some reason, the routines Array becomes null during runtime, except when the name of the clicked day on the first page is empty. This anomaly seems related to my unconventional storage system, but I'm unable to identify the exact culprit.

The page name was Upper Body home.ts:63:4
PRE CONSTRUCTOR routine.ts:28:4
ROUTINES ARRAY before getRoutine() routine.ts:46:4
ROUTINES ARRAY after getRoutine() [object Object] routine.ts:51:4
POST CONSTRUCTOR [object Object] routine.ts:32:4
ARRAY BEFORE ALERT: null routine.ts:91:4
ARRAY AFTER ALERT: null routine.ts:93:4
ROUTINES ARRAY AFTER SAVE BUTTON PRESS:null routine.ts:85:12
ROUTINES ARRAY before addRoutine() null

After the constructor completes, the array suddenly becomes null. What could be causing this? I need fresh insight to overcome this challenge.

Answer №1

After seeking assistance from SO, I managed to resolve the issue. The problem was that the promise generated by storage.get('ArrayKey') was returning `null` because the specified storage did not exist in my app. To solve this, I first checked if the promise returned by storage.get('ArrayKey') was null. If it was, I used storage.set('ArrayKey') to store an empty array as the default value. Then, I retrieved the value using storage.get('ArrayKey'). This time it worked because the array was now empty but not `null`.

I realize that with this title, it may be unlikely for someone facing the same issue to come across this solution. However, if you do find this helpful, cheers and thank you for the assistance.

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 is the best way to incorporate a line into a scene using three.js?

I am facing an issue with adding a line in three.js. When I call the addline function in my code, the line doesn't appear in the scene. I have tried to implement the MVC design pattern, but I am unsure where I went wrong. Thank you for any assistance ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

Clone the children of an li element using jQuery, modify the text within a child tag, and then add it to

I have some awesome CSS that I want to recycle within a <ul>. My plan is to duplicate an existing <li> (to leverage the CSS), modify a <p> element, and then add it at the end of the <ul>. I believe I can achieve this by locating... ...

Incorporating a Favicon into your NextJs App routing system

Encountering an issue with the new Next.js App Router. The head.js files have been removed, thus according to the documentation I need to implement metadata in layout.ts. My favicon file is named favicon.png. How should I specify it within the following c ...

Tips to store Google fonts in the assets directory

I've included this link in my styles.scss @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'); While it works locally, the API fails on production or is blocked. How can I host it within my p ...

Event for Angular 4 mat-datepicker triggering on date selection change

I currently have a date picker feature implemented in my application. Here is the code snippet: <mat-form-field> <input mdInput [matDatepicker]="dp3" placeholder="Select Birthday" name="birthday" disabled> <mat-datepicker-toggle ...

Obtaining the innerHTML value using JavaScript in an Asp.net Core 5 View

Apologies for any inaccuracies in my English writing. In the Asp.Net Core project view, I am trying to use JavaScript to capture multiple Span tags within innerHTML represented by a loop and display their sum in another tag. However, I am only able to ret ...

The combination of setInterval() and if(confirm()) is not possible in pure JavaScript

One day, I encountered a simple if(confirm()) condition like this: if(confirm('Some question')) { agreed_function(); } else { cancel_function(); } function agreed_function() { console.log('OK'); } function cancel_function( ...

Completely charting the dimensions of an unfamiliar object (and the most effective method for determining its extent)

I am facing a challenge with a "parent" object that contains an unknown number of children at various depths. My main objective is to efficiently map this "parent" object and all its levels of children. How can I achieve this task? Each child already inc ...

Guide to Inputting Numbers in a Form Field using a Pop-up Keypad (with Javascript/AJAX)

I am working on a small project that involves creating a keypad with buttons for all the digits, backspace, and decimal. When these buttons are clicked, they should populate a form field like a text box. The keypad will be located next to the form field as ...

Using jQuery and CSS to Filter and Sort Content

I need help with filtering a list of content based on their class names. The goal is to show specific items when a user clicks on one of two menus. Some items have multiple classes and users should be able to filter by both menus simultaneously. Currently ...

Struggling with the @typescript-eslint/no-var-requires error when trying to include @axe-core/react? Here's a step-by

I have integrated axe-core/react into my project by: npm install --save-dev @axe-core/react Now, to make it work, I included the following code snippet in my index.tsx file: if (process.env.NODE_ENV !== 'production') { const axe = require(&a ...

I am trying to locate the XPath for the NG repeat element with the following code snippet: ng-repeat="thread in threads | orderBy:'-last_ts' | filter : globalSearch track by $index" Can you assist

<div ng-click="changeChatThread(thread, true)" class="item ui three column grid thread_item ng-scope active-thread" ng-class="{'active-thread' : selectedThread === thread.chat_id}" ng-repeat="thread in threads | orderBy:'-last_ts' | ...

Tips for preventing redirection in Vue 3 composition API with asynchronous requests

I have successfully configured a submission form to send data to my email and add it to a Google sheet using the method described in this GitHub link. The process worked seamlessly for both purposes. However, I am facing an issue where upon submitting the ...

Tomickigrzegorz Script Finder Predictive Search

Hey there, I recently tried out the autocomplete script created by tomickigrzegorz. Check it out here! It's been working smoothly for me, but I'm facing an issue with external link tags like https//google.com not functioning properly. Here is ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

Manipulating Objects and Arrays

When I retrieve data from a database query in Node.js using Postgres with Knex, I get an array of objects structured like this: (condensed version) [ { tvshow: 'house', airdate: 2017-02-01T00:00:00.000Z }, { tvshow: ' ...

Error encountered: unable to locate module - '@deck.gl/exper-layers'

When attempting to run npm start on the trip example in deck.gl, I encountered an issue. Although other examples open without any problems, the trip example is giving me this npm error: Module not found: Error: Can't resolve '@deck.gl/experim ...

What is the best way to modify the height of a div before fetching an image using Ajax, and then revert it back to its original height once the image has been

Using a form and Ajax, I'm dynamically pulling an image to replace another image in the .results div. Initially, when the image was removed and loaded, the page jumped up and down, so I tried adding a style attribute to set the div height and then rem ...

What is the method to determine the index of a removed element within a subarray?

In my array, all = [2,3,4,12, 55,33], there is a sub-array named ar1 = [12, 55, 33] starting from the value 12. If I remove a value from all that is present in ar1 (e.g. 12), how can I determine the index of this value in ar1 (0 for 12) so I can also remo ...