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

Transfer data as JSON from Flask to JavaScript

Having trouble sending data from Flask to JavaScript. I have the information from the database and added it to a dictionary. Now, I want to convert this data into a JSON object in JavaScript to display it on a map. Despite using JSON.parse in JavaScript, i ...

Incorporate any enum value into a Typescript interface

I'm working with a Typescript interface export interface MyInterface { valid: boolean; resourceType: MyEnum; message: string; } As well as an enum enum MyEnum { 'a', 'b', 'c' } Is there a way to allow the ...

Alternative way to search for child elements within an element without the use of jQuery

I am in the process of creating a universal set of functions to verify the existence of children with specific attributes within a particular element. Unfortunately, I do not have access to jQuery for this task. Here is an example function call: has_chil ...

Tips for identifying when a tab has been reopened following closure?

There seems to be a problem with the JS state where it changes but then reverts back to its original state when the tab is closed and restored using cmd/ctrl + shift + t. Typically, data is fetched from the server via ajax using Vue's mounted() lifec ...

Explore the Ability to Monitor Modifications to an Object's Property in Angular2/Typescript

Can we track changes to an object's field in Angular2/Typescript? For instance, if we have a class Person with fields firstName, lastName, and fullName, is it feasible to automatically modify fullName whenever either firstName or lastName is altered? ...

The signature provided by the pusher is invalid: The expected HMAC SHA256 in hexadecimal digest is

The HTML file contains JavaScript code that calls the server for authentication. The code snippet from the HTML file is as follows: <html> <script> <head> var options = { authEndpoint: "api/pusher.json?socket_id=9900&channel_name ...

The correct terminology for divs, spans, paragraphs, images, anchor tags, table rows, table data, unordered lists, list

Just wondering, I've noticed that every time I come across a page element '<###>[content]<###>' and want to learn how to manipulate it, I usually search for something like "how to do x with div" or "how to get y from div". I know that ...

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

The integration between Javascript, PHP, and SQL Server does not display the retrieved data

I am a beginner in PHP and have limited knowledge of Javascript. I am attempting to create a chronometer where the time limit is retrieved from a SQL SERVER database. However, when I assign the value obtained in PHP to a Javascript variable, it returns -1. ...

Utilizing the <style scoped> feature within my Angular template

When adding CSS styles in the specified htm file's templateUrl while loading a directive, I wonder if this is a bad idea. Will it be repeated every time the template is instantiated on the rendered page, or does Angular handle this differently? By usi ...

Can we use classlist for adding or removing in Angular 2?

One of the features in my project is a directive that allows drag and drop functionality for elements. While dragging an element, I am applying classes to both the dragged element and the ones it's being dragged over. This is how I currently handle it ...

What is the importance of having the same data type for the searchElement in the argument for Array.prototype.includes()?

Is there an issue with my settings or is this a feature of TypeScript? Consider the code snippet below: type AllowedChars = 'x' | 'y' | 'z'; const exampleArr: AllowedChars[] = ['x', 'y', 'z']; f ...

Having trouble passing arguments to button methods in jasmine when applying vue and moment libraries

I am working on unit testing a Vue app using `jasmine` and `karma`. Here is an example of the code inside one of my components: After fetching data from a database with `v-for=(data,index)`, I am displaying the `data.date` in the template: <p class=&qu ...

JavaScript: Extending a class with an invalid or null value is not permitted

Trying my hand at constructing a page object for login testing with WebdriverIO. Encountering the error ERROR: Class extends value #<Page> is not a function or null on line 3 of login.page.js. No clue what mistake I'm making... Is there a wron ...

Bidirectional data binding in Angular 2 allows for communication between parent components and directives

Update: Experimenting with Angular2 Beta, I am working on incorporating an "editor" component template that includes a directive wrapping the Ace editor. In this scenario, the "editor" component acts as the parent of the Ace wrapper directive, and my goal ...

Troub3leshooting Circular Dependency with Typescript, CommonJS & Browserify

I am currently in the process of transitioning a rather substantial TypeScript project from internal modules to external modules. The main reason behind this move is to establish a single core bundle that has the capability to load additional bundles if an ...

Add a third-party library file to Visual Studio

I'm currently working in Visual Studios and attempting to utilize the library provided at . However, I am encountering difficulties when trying to import the library. I have added the file to the project and attempted to use it within the Book.js (Vi ...

TypeScript perplexed Babel with its unfamiliar syntax and could not compile it

Encountered a problem while attempting to compile typescript. It appears that babel was unable to comprehend the "?." syntax on the line node.current?.contains(event.target) export function useOnClickOutside(node: any, handler: any) { const handlerRef = ...

Prevent selection of future dates in Kendo UI Calendar Widget

Can someone please advise on a method to disable future dates (i.e., gray them out) in the Kendo UI Calendar widget? I've attempted hiding the future dates, but it doesn't look good. I've also tried different ways to gray them out without su ...

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...