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

"Internet Explorer naturally selects the submit button when users press the enter key to submit a

In my current application, I have implemented a form with a hidden button to address issues with the numeric keyboard on Android. Essentially, pressing enter or focusing on the invisible button will trigger form submission. Pressing enter works fine in Ch ...

Creating reversed/generate URLs from Routes in Angular2 (using typescript)

Is there a way to automatically create a URL from a route using code? For instance, let's say I have a login component defined in my routes: const appRoutes: Routes = [ ... { path: 'login', component: LoginComponent }, ... ]; N ...

Is there a method available that functions akin to document.getelementbyid() in this specific scenario?

Currently, I am tackling a project that involves implementing a search function. My initial step is to ensure that all input is converted to lowercase in order to simplify SQL calls. However, I have encountered a challenge that is proving difficult for me ...

Guide on incorporating Vue components: implementing component 2 within the template of component 1

I'm a Vue beginner and struggling with how to use one component within the template of another or how to combine them in HTML. I've tried looking through the documentation and Stack Overflow but can't seem to figure it out. Currently, I am ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

Enhancing current interfaces

I'm exploring Koa and the module system in Node.js. Although I'm not asking about a specific koa question, all the code I'm working with involves using koa. In Koa, every request is defined by the Request interface: declare module "koa" { ...

Is there a way to verify that all images have been successfully loaded following an

Is it possible to determine when all images have finished loading from an appended HTML source in order to trigger another function? $(document).ready(function () { $('a.load-more').click(function (e) { e.preventDefault(); $.ajax({ ...

Missing pieces of data | Utilizing React and Redux Toolkit

I'm facing a problem that's keeping me up for almost 24 hours. I just finished coding this slice, but when I submit the data, only the automatically generated ID is returned. Let me explain further - I have a skill component with two input forms ...

Error encountered in Angular: FormBuilder provider not found

I am currently utilizing Angular 9. An error that I am encountering is as follows: No provider for FormBuilder This issue has been documented in numerous instances, with the common solution being to include the FormsModule in the app.module.ts file. F ...

Newbie in JavaScript - reinitiating my for loop journey

After running an animation in 4 steps, I want it to restart once all the steps are completed. var aSteps = [ { "x": "800", "y": "0" }, { "x": "800", "y": "500" }, { "x": "0", "y": "500" ...

The jQuery Validate Plugin only validates emails when the user moves away from the input field

Resolved: Upon inspecting my version of jquery-validate.js, I discovered that it was missing the onkeyup handler. Despite using version 1.12 Opre, which should have had this functionality according to its Github history from 2013, it seemed like there may ...

Removing scrollbar from table in React using Material UI

I successfully created a basic table using react and material UI by following the instructions found at: https://material-ui.com/components/tables/#table. The table is functioning properly, but I am finding the scrollbar to be a bit inconvenient. https:// ...

Jest test encounters Firebase initialization error

Testing event handlers for a slack bolt app has been quite the rollercoaster. Initially, all tests passed flawlessly, making life wonderful. However, after some refactoring, the entire test suite failed to run, displaying an error indicating that firebase ...

Steps to converting an enum or literal

Hey there, I'm relatively new to working with TypeScript and I've been experimenting with transforming enums/literals using functions. For instance, creating a capitalize function that capitalizes the first letter of a string. (e.g., mapping typ ...

retrieving serialized object from an ajax request sent to the web server

As a newcomer to web development, I decided to create an ASP.NET project with a web API to test my skills. In the process, I crafted a controller and some JavaScript files as follows: Controller: namespace MyNamespace.Controllers { public c ...

What is the best way to transmit a 500x500 2D Integer Array using Websockets?

I'm encountering an issue where I believe it may be too time-consuming to JSON.stringify and send data to each individual user. For example, if 4 people connect at the same time, the server will become stalled during array parsing, resulting in signif ...

What is the best way to develop a JavaScript function that divides the total width by the number of table headers (`th`)?

I recently came across this amazing scrollable table on a website, but I'm facing an issue with resizing the headers equally. Due to my lack of knowledge in JavaScript, I'm uncertain about how to tackle this problem. My intuition tells me that a ...

Improving HTML coding with a more effective alternative to document.write()

Looking at the setup of my website, I have a menu button and comments section that need to appear on every page. Instead of manually adding this code to each HTML file, I decided to streamline the process by using a JavaScript file that generates all of th ...

Tips for maintaining the selection when switching pages with smart-table?

I have implemented smart-table in my project to allow users to select records from different pages and view them in a preview section. However, I am facing an issue where the selection made on the first page does not persist when navigating back to it aft ...

TRPC fails to respond to the passed configuration or variables (e.g., when enabled is set to false)

Recently started using trpc and I'm trying to grasp how to utilize useQuery (which I've previously worked with in react-query): const IndexPage = () => { const { isLoading, data, isIdle } = trpc.useQuery([ "subscriber.add", { email: ...