Preventing data loss in an Ionic array - encountering issues with using this.array.push

When attempting to use the storage get method to fill the array storedArr = [], I encounter the error message .push is not a function:

storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : [];

The crucial section of my code looks like this:

import { Storage } from '@ionic/storage';

export class MyPage {
    constructor(
        private storage: Storage) {
    }

    // storedArr = []; This approach works but resets the array

    storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : [];

    saveToStorage() {
        this.storedArr.push({ // .push is not a function
          title: 'blabla',
          body: 'more blabla'
        });

        this.storage.set('stored', this.storedArr);
    }
}

How can I modify that section of the code for it to work properly?

Answer №1

The concept of Ionic's this.storage.get is that it returns a promise rather than an immediate value, which needs to be "subscribed" to in order to obtain the actual data.

When using

storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : [];
, it stores a promise inside storedArr on success, and still returns a promise even if it fails. This leads to an error because the Promise prototype does not have the push method. Therefore, the ternary operator resolves to true and [] will not get assigned to storedArr.

To correctly retrieve the value from this.storage.get('stored') in Ionic, you must subscribe to the returned promise and then assign the data parameter to storedArr. Here's how it should be done...

export class MyPage {
  storedArr = [];

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

  saveToStorage() {
      this.storedArr.push({ // .push is not a function
        title: 'blabla',
        body: 'more blabla'
      });

      this.storage.set('stored', this.storedArr);
  }
}

Answer №2

In the case where you are storing something more complex than a basic primitive value, it is necessary to use JSON.parse() on the result obtained from the storage getter. The code snippet below demonstrates how this can be done. I have made use of the await keyword instead of using then for clarity.

var storageResult = await this.storage.get('stored');
storedArr = (storageResult) ? JSON.parse(storageResult) : [];

Furthermore, when you are storing an array, it is recommended to use JSON.stringify before saving it.

this.storage.set('stored', JSON.stringify(this.storedArr));

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

Challenges encountered while developing Angular FormArrays: Managing value changes, applying validators, and resolving checkbox deselection

I am facing an issue with my Angular formArray of checkboxes. In order to ensure that at least one checkbox is selected, I have implemented a validator. However, there are two problems that I need to address: Firstly, when the last checkbox is selecte ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

How to bring in images from the assets folder using React and Typescript

I'm facing an issue where direct image importing is working, but when using object types, it's not functioning properly. Why could this be happening? I am currently working with "react": "^16.12.0" and "typescript": "~3.7.2" // ./src/assets/baby ...

"Unlocking the full potential of Typescript and Redux: Streamlining the use of 'connect' without the need to

I am facing some challenges with typescript and redux-thunk actions. The issue arises when my components heavily rely on react-redux connect to bind action creators. The problem occurs when I create the interface for these redux actions within the compone ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

What is the process for mocking a method from a class that is instantiated within another class using ts mockito in typescript?

I have a specific Class that I want to test using the mocha-chai testing framework in TypeScript. My approach involves incorporating ts-mockito for mocking purposes. export class MainClass implements IMainClass { private mainResource: IMainResource; ...

Encountering this issue? Error TS2304: Name not found

When I attempt to run unit tests for my Angular application using 'ng test', I encounter the error message: "Error TS2304: Cannot find name.." Interestingly, running 'ng serve' works without any issues. I followed a guide (link provide ...

How can you restrict the number of characters a user can input into an Angular input textbox?

I am using the textarea tag and I would like to limit the number of characters a user can type to 300. Currently, I have implemented real-time character count functionality, but I need to restrict input once it reaches 300 characters. Below is my HTML cod ...

How can I combine multiple requests in RxJS, executing one request at a time in parallel, and receiving a single combined result?

For instance, assume I have 2 API services that return data in the form of Observables. function add(row) { let r = Math.ceil(Math.random() * 2000); let k = row + 1; return timer(r).pipe(mapTo(k)); } function multiple(row) { let r = Math.c ...

"Conceal Digits with SweetAlert2's Number Mask

Could you assist me in adding a number mask to an input field in sweetalert2? Here is my code: onClick(btn) { let code2_fa = ''; if (JSON.parse(localStorage.getItem('user')).password.two_factors.is_active) { swal({ ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

Executing a designated assessment in Protractor

Is there a way to run a specific test scenario in my Angular app? I recently added a new feature in Protractor, created the necessary page and steps, but I already have other features implemented. I am wondering if it is possible to solely test the new f ...

What is the most effective method to verify if all elements in an array fall within a specified range

What is the most effective method to verify if all array values fall within a specific range? For instance: $range = range(10, 40); $array1 = array(10, 20, 40); // OK $array2 = array(11, 22, 42, 30); // FALSE $array3 = array(50); // OK $array4 = arra ...

Click the link to copy it and then paste the hyperlink

I am facing an issue with copying and pasting file names as hyperlinks. I have checkboxes next to multiple files and a share button. When I check the boxes and click on the share button, I want to copy the download URLs for those files. Although I can succ ...

In the context of Angular applications, how can a state be defined?

Exploring the world of NgRx for the first time and diving into its documentation, I stumbled upon this statement: "State is a single, immutable data structure." In plain terms, what exactly does "state" refer to? Can you provide some basic examples to ...

What sets apart ".. let i = index" from "..let i as index"?

Having recently delved into the world of Angular, I've been scouring YouTube for tutorials. While watching, I noticed some developers using ""let item of items; let i as index"" while others used ""let item of items; let i = index" ...

Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows: [{value: "a", start: 1950, end: 1954, description: "aaa"}, {value: "b", start: 1953, end: 1956, description: "bbb"}, {value: "c", start: 1960, end: 1962, des ...

Angular 2 offers the ability to crop and save images effortlessly

Utilizing ngImgCrop, I have been able to upload images and crop them successfully. Now, I am trying to figure out how to save the result-image from <img-crop image="myImage" result-image="myCroppedImage"></img-crop> to a folder in ASP.NET MV ...

Can you iterate through two arrays to find common values?

Upon examining my firebase database, I found the following structure: Users { askdfasdf: John: { Selection: [1,2,3] }, fasfadffe: Mark: { Selection: [1,2,4] } } Players { { name: &apos ...

How can I use req.value in Node.js Express middleware to set values for uploading options in Ionic Cordova FileTransfer?

I am a beginner with Ionic and currently working on uploading a file to a server. My main goal is to include a json object along with the FileTransfer.upload request from the client side, and then retrieve this object on the server using an express middlew ...