Clear out the existing elements in the array and replace them with fresh values

Within my Progressive Web App, I am utilizing HTTP requests to populate flip cards with responses. The content of the requests relies on the selected values.

An issue arises when I choose an item from the dropdown menu. It triggers a request and displays the flip cards populated by that response. However, upon selecting another item, it creates a new request and adds additional cards without clearing the view (array) from the previous cards.

The searchByIngredient.component.ts

search() {
    this.drinksapi.get(this.selectedIngredient.name).subscribe(data => {
      const a = data[`drinks`];
      a.map((y: { idDrink: any; }) => this.drinksapi.detailsCocktails(y.idDrink).subscribe(res => {
        const b = res[`drinks`];
        for (y of b) {
          const obj = Object.assign({}, y);
          this.onSearch.emit(obj);
        }
      }));
    });
  }

Navbar(dropdown).component.html

<ng-select [items]="ingredients"
                   bindLabel="name"
                   placeholder="Search By Ingredient"
                   [(ngModel)]="selectedIngredient"
                   (ngModelChange)="search()">
        </ng-select>

App.Component.ts (likely containing the issue)

export class AppComponent {
  title = 'CocktailDB';
  drinks: Array<any> = [];

  onSearch($event: any) {
    // this.drinks.length = 0;
    if (this.drinks !== []) {
      this.drinks.push($event);
    }
    console.log('drinks', this.drinks);
  } // end onSearch

I have also observed receiving "Drinks" one by one, here's a screenshot of the console

Depending on "this.drinks.length", I either receive an array where each new card is combined with the old ones, or only a single card is displayed (updated by the selected ingredient)...Yet, I am unclear on how to address this issue...My goal is simply to update the view (and empty the array) every time I select an item

Answer №1

Instead of triggering this.onSearch.emit() in every loop iteration, consider building your array with the results from both API calls first.

After constructing the array, trigger this.onSearch.emit() to set the this.drinks array using: this.drinks = $event

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

An error occurred while trying to add a property to an array because the object is not extensible: TypeError -

In my code, there is an object named curNode with the following structure: { "name": "CAMPAIGN", "attributes": {}, "children": [] } I am attempting to add a new node to the object like this: curNode!.children!.push({ name: newNodeName, ...

Utilizing ASP.NET Core MVC in conjunction with Angular and Identity Server 4 for seamless integration with web API connections

Posting here after receiving a response from this post -------------------------------------- In the midst of developing an application with an MVC core app that loads an angular application. The angular app will connect to a Web API for CRUD operations. ...

Creating a reusable field for reactive forms in Angular: A step-by-step guide

I need assistance with creating a versatile field component for reactive forms, but I am facing challenges in retrieving the value from the custom-input element. <form [formGroup]="form" (ngSubmit)="submit()"> <custom-input i ...

Changing text color based on positive or negative value in JavaScript(React)

Greetings everyone! I'm currently working on a specific feature that requires the color of a value to change dynamically. If the value is above 0, it should be displayed in green; if below 0, in red; and if equal to 0, in orange or yellow. To achieve ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

Angular 7 form does not automatically disable the button upon initialization

My current challenge involves disabling a button until a form is completely filled out. Surprisingly, everything works perfectly in Chrome and Firefox, but IE11 seems to be causing some issues. Below is the relevant code snippet: <div class="col-12"> ...

What is the best way to transfer scope to a callback function in the context of node-mysql?

When running the code below, I encounter an error that says client is not defined: var mysql = require('mysql'); var conf = { 'database':'database', 'user':'user', 'password':'password ...

Creating a definition for the use of sweet alerts within a service and incorporating them through

Implementing sweet alert for displaying alert messages in angularJS2/typescript. Due to the repetitive nature of this code in different parts of the application, a service was created. @Injectable() export class AlertMessageService { constructor(pr ...

Trouble updating document with MongoDB updateOne when using ID as filter

I need to update a property value of a specific document by sending a request to my NextJs API using fetch. // Update items in state when the pending time in queue has passed, set allowed: true items.map((item) => { const itemDate = new Date(item.adde ...

How to delay setting a property in Angular 2 until the previous setter has finished execution

Hey there, I'm facing an issue with my component. Within my component, I have an input setter set up like this: @Input() set editStatus(status: boolean) { this.savedEditStatus = status; if (this.savedEditStatus === true && this.getTrigg === t ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

Using Vue Formulate to effortlessly upload multiple images

One of my projects involves using a Vue Formulate component for uploading multiple images to an Express.js backend. Here is the code snippet for the Vue Formulate component: <FormulateInput type="image" name="property_ ...

Error in uploading files with Node.js, Multer, and Angular - issue with setting headers after they have already been sent

Working with Angular 5, Node.js, and Multer to upload a file. The process involves first saving the file to a directory and then inserting the path into the database. To begin, I created a form: <input type="file" (change)="onFileSelected($event)"> ...

Including variables in package.jsonORInjecting variables into package

I'm currently developing a React application and I am trying to figure out how to pass a variable from the .env file into package.json: {"proxy": "ENV_VAR"} Is there a way to achieve this? In addition, our app is built using Docker. Is it possible ...

There was an error in Index.js: The UserForm component did not return anything from the render function. This typically occurs when a return statement is missing. To render nothing, you can return

Hello, I'm a beginner with React and I'm attempting to add a row in my React app when a button is clicked. I referenced this guide on how to dynamically add and remove table rows in React.js However, I'm having trouble adapting it to my cod ...

What could be the reason for the React component not re-rendering even after its prop has been updated?

One of the challenges I'm facing with an application I'm currently working on is a re-render issue. To simplify, let's say we have two components - DisplayElement1 and DisplayElement2. In this scenario, DisplayElement2 iterates through a ba ...

The functionality of nested routing is not operating properly in react-router

I'm currently struggling to get my CollectionPage to render and match the URL correctly within my nested Route in React. Unfortunately, it doesn't seem to be working as expected! Here's a piece of code from my shop.component file that is be ...

Having trouble with my router in the express app - the .find and .findByID methods are not working properly. Also,

In my current setup with NextJS/MERN stack, I am using the server.js file in NextJS to import API routes and make API calls. The routes seem to be functioning properly as there is activity when calling them from Postman or the browser. However, it appears ...

The React router Link does not update the route after an if statement is executed

I'm in need of some assistance regarding React.js. Despite my efforts to find a solution, nothing has worked for me so far. Here are some examples of what I've searched for: How to use Redirect in the new react-router-dom of Reactjs Redirectin ...

Adjust the color of the glyphicon icon within a date and time picker dropdown component

I decided to implement the bootstrap datetimepicker using this gem and utilized the following HTML code: <div id="custom-dates" style=" clear:both;"> <div class="container"> <div class="row"> <div class='col-md-3 col-xs-3' ...