The shopping list feature is unable to save or list multiple recipes at once

My goal is to:

  1. Create a shopping list that retrieves recipes from an API.
  2. Transfer ingredients from one page to another.
  3. Automatically refresh/load data when more than 1 item is added.

The challenge I am facing is:

  1. Only one set of ingredients loads.
  2. The clear function does not allow for adding more items.

Recipe Page

// Loading Recipes 
/////////////////////////////////////////////////////////////////////

loadDetails1(id){
    this.apiAuthentication.loadDetails(id)
    .then(data => {
        this.api = data;
    });
}

// Add to Shopping List 
///////////////////////////////////////////////////////////////////// 

submit(api) {

    let toast = this.toastCtrl.create({
      message: 'Added to shopping list',
      duration: 1000
    });

    console.log(this.api);

    this.storage.get('myData').then((api) => {

        // add one ingredient to the ingredientLines object
        // if it's still a string use JSON.parse() on it
        this.storage.set('myData', api).then(result =>{
            toast.present();
            console.log(api);
        }); 
    }); 
}

HTML

<h1 (click)="submit(api?.ingredientLines)">Add to shopping list</h1> 
<ul>
    <li *ngFor="let item of api?.ingredientLines"><span>{{item}}</span></li>
</ul>

Shopping List Page

getData() {
  this.storage.get('myData').then((data => {
      this.api = data;
      console.log(data);

      setInterval(() => {
        console.log(data);
      },5000);
  }));
}

HTML

<ion-content padding>
    <ion-card>
        <ion-card-header>
            {{api?.name}}
        </ion-card-header>

        <ion-list>
            <ion-item>
                <ul>
                    <li *ngFor="let item of api?.ingredientLines">
                        <ion-label>{{item}}</ion-label>
                        <ion-checkbox></ion-checkbox>
                    </li>
                </ul>
            </ion-item>
        </ion-list>
        <button ion-button block full color="danger" (click)="clear(item)">Remove</button>
    </ion-card>
</ion-content>

Shopping list page image can be seen here: https://i.sstatic.net/Up5Oz.png

Error shown in visual is https://www.youtube.com/watch?v=BDS_XTdw2S0. The issue is that when an item is added to the shopping list, it does not update until the app is closed and restarted. Additionally, only one item is displayed at a time.

Answer №1

By continuously overwriting your storage, you may only see one item displayed.

To prevent this issue, consider utilizing type annotations and promises

public addToShoppingList(ingredientLines: any) {

let toast = this.toastCtrl.create({
    message: 'Item added to shopping list',
    duration: 1000
});

this.storage.get('myData').then((ingredientLines) => {

    console.log(ingredientLines);

    // Incorporate a new ingredient into the existing data
    // If it's still in string format, utilize JSON.parse() to convert
    this.storage.set('myData', ingredientLines).then(result =>{
        toast.present();
    }); 
}); 
}

The process involves:

  1. Retrieving data from storage

  2. Adding a new item to the existing data

  3. Saving the updated data back to storage

Answer №2

To efficiently manage and connect all the components, I utilized a template to bind them together as objects.

.html file

<template ngFor let-api [ngForOf]="shoppingList">
    <ion-card>
        <ion-card-header>
            {{api?.name}}
        </ion-card-header>
        <ion-list inset>
            <ion-item *ngFor="let ingredient of api.ingredientLines">
                <ion-label>{{ ingredient }}</ion-label>
                <ion-checkbox item-right></ion-checkbox>
            </ion-item>
        </ion-list>
        <button ion-button block full color="danger" (click)="clear(api)">Remove</button>
    </ion-card>
</template>

and .ts file is

public submit(api: any) {

    let toast = this.toastCtrl.create({
      message: 'Added to shopping list',
      duration: 1000
    });

    console.log(this.api);
    var thisRecipe = this.api;

    this.storage.get('shoppingList').then((shoppingList) => {
        if(!shoppingList){
            shoppingList = [];
        }

       shoppingList.push(thisRecipe);

        this.storage.set('shoppingList', shoppingList).then(result => {
            console.log("Added to Shopping List", result);
            toast.present();
        });
    });
}

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

Testing Angular Components with setInterval FunctionTrying out unit tests in Angular

I'm struggling to figure out how to write unit tests for setInterval in my .component.ts file. Here is the function I have: startTimer() { this.showResend = false; this.otpError = false; this.time = 60; this.interval = setInterval(() => { this.ti ...

Establishing predefined values for formArray in Angular 6

Contact Information Model, interface ContactInfo { name:string; age:number; } Contact Information Component, initializing contacts array with some default values , export class ContactInfoComponent { contacts: ContactInfo[] = [{name:'John Doe ...

What methods can I use to integrate a Google HeatMap into the GoogleMap object in the Angular AGM library?

I am trying to fetch the googleMap object in agm and utilize it to create a HeatMapLayer in my project. However, the following code is not functioning as expected: declare var google: any; @Directive({ selector: 'my-comp', }) export class MyC ...

nativescript input value binding

<StackLayout> <Label text="Enter the station name:"></Label> <TextField hint="Station name" col="0" [ngModel]="stationName" (ngModelChange)="stationTyping($event)"></TextField> </StackLayout> An error is occurri ...

Guide to showcasing an image obtained from a Web API in Angular

I have a unique challenge with displaying images on the user interface. The image data is retrieved from a database through a web API, and the image path is stored in the DB's imagePath column. However, when fetching the data via the web API, only the ...

Issue with Angular authentication during login attempt

I am a beginner in Angular and I'm using this method to allow users to log into the system. loginuser(){ const user = { username: this.username, password: this.password }; this.Auth.loginUser(user).subscribe((res)=>{ ...

Facing issues while trying to deploy my Angular 5 application on Heroku

I've encountered an issue while attempting to deploy my Angular 5 project on Heroku. While I've successfully deployed other projects before, this one seems to have a dependency problem that is hindering the process. Locally, running ng build pos ...

Using various functions to set values in AngularJS

I am facing a small issue where I am calling a service method within one function and then trying to access the values from that function in another function within the same controller. However, when attempting to access the values, it shows that they are ...

The Primeng Angular2 checkbox malfunctioning issue

My form setup in Angular2 CLI looks like this: Inside the component export class UsersAddComponent implements OnInit { ngOnInit() { this.userForm = this._formBuilder.group({ role: ['', [Validators.required]], others: this._for ...

Building ASP.NET MVC4 with TypeScript 2.x and experimentalDecorators using TFS 2015 xaml build process

Our TFS 2015 setup incorporates "old" xaml Builds and now I am looking to deploy an Angular 2 website with webpack. I have successfully installed npm and compiled my project using webpack on the tfs by including a simple Target. Everything seems to be wor ...

How to replace/redirect the import statement in TypeScript from { X } to 'Y'

My situation involves an external library known as Y, which was installed using npm and loaded from the node_modules directory. This library is hosted on GitHub and currently being utilized in my project in the following manner: import { X } from 'Y& ...

Issue with displaying data on a Modal in Angular when clicking for the first time, but successfully displays on the second click

In my display screen, customer details are shown in a table format. When a row is clicked, a modal should pop up displaying detailed information about the customer. The issue I'm facing is that data is not populated on the first click, but it works fi ...

Do you think it's essential to subscribe and unsubscribe from observables in these scenarios?

Contemplating observables has brought me to consider the following scenarios: Scenario 1) In my use of NGRX, I diligently set up the architecture and create a selector service for a specific store. In this service, the absence of ngOnDestroy raises a que ...

Leveraging Angular 9 pipes to transform an array by applying a filter that utilizes a function to return an observable

Looking for a way to filter an array using a function that returns an observable boolean has been a challenge. The goal is to have a pipe that filters values based on a user's permissions, considering that permissions are observable and may not be av ...

ERROR: Issue detected in the e class under the e_Host - inline template 0:0

As I was upgrading my angular2 project to RC5, a major issue surfaced. Despite reducing all the code to its minimum in order to debug the problem, I couldn't pinpoint its origin. Every request made by my app led to the following error message (as seen ...

Error encountered during module parsing: Token found was not as expected in Webpack 4

When I run my builds, webpack keeps throwing this error: ERROR in ./client/components/App/index.tsx 15:9 Module parse failed: Unexpected token (15:9) You may need an appropriate loader to handle this file type. | | > const App: SFC = () => ( ...

What is the process for moving data from the store to the form?

When retrieving data from the store, I typically use the following method: ngOnInit(): void { this.store.pipe(select(getPerson)) this.store.dispatch(loadPerson()); } However, I am now faced with the challenge of transferring this data from the ...

The Component TSX is reporting a Type error stating that the Property 'onChange' is not present in the type '{ key: string; value: Model; }' as required by Props

While running the following command: npm run build I encountered an error that needs resolution: /components/Lane.tsx:37:18 Type error: Property 'onChange' is missing in type '{ key: string; value: StepModel; }' but required in type &a ...

Updating the state in React Native does not occur

I'm facing an issue where I can't seem to update the state using useState while coding in React Native. The component in question is a styled TextInput named SearchField. Can anyone help me figure out what I might be doing wrong that's preve ...

Evaluation of code coverage with respect to mouse event tests is inadequate

I am currently writing a jasmine test in angular in order to achieve full code coverage. The main focus of the test is to cover the click events of a specific component. Although the tests pass individually, the code coverage report indicates that the func ...