Utilizing lodash and Angular 8: Identifying an valid array index then verifying with an if statement

In my current project, I am developing an e-commerce angular application that includes a basket with two types of products: restaurant + show combos and gift cards. When a client reserves a restaurant, they must also reserve a show; conversely, the client can add multiple restaurant/show combos and multiple gift cards to the basket. The command button will be disabled if:

1- A restaurant/show combo is missing one item (either restaurant or show).

Below is the HTML for the basket:

<div id="mySidenavv" class="sidenavv">
  <div class="mySidenavv-content">
    <div class="row">
      <div class="col-md-8 Mon-panier ">Mon panier </div>
      <div class="col-md-2"> <a href="javascript:void(0)" class="closebtn" (click)="closeSideNav()"><img
            src="/assets/img/double-right-arrows-angles.png" alt="">
        </a></div>
    </div>
    <div class="row Divider"></div>
    <div class="item-container">
      ... (content continues)
          ...
    </div>
  </div>
</div>

Furthermore, in the respective TypeScript file:

ngOnInit() {
    this.serverUrl = environment.serverUrl
    this.cartService.myCart$.subscribe(res => {
      this.total = 0
      this.giftCardsTotal = 0
      this.cartItems = this.cartService.getItemCard() || res

      // Check conditions for disabling the book button
      let indexEmptyItem = -1;
      let giftItemIndex = -1;
      for (let i=0; i<this.cartItems.length; i++) {
          if ((!this.cartItems[i].restaurant || !this.cartItems[i].spectacle || !this.cartItems[i].placesListContent || this.cartItems[i].placesListContent.length < 1)) {
              indexEmptyItem = i;
          }
          if (!this.cartItems[i].type) {
              giftItemIndex = i;
          }
      }

      if (indexEmptyItem == -1 || giftItemIndex == -1) {
          this.disableBookBtn = false;
      } else {
          this.disableBookBtn = true;
      }

      // Calculate total prices
      this.cartItems.forEach(item => {
          if (item.spectacle) {
              this.total += item.qte * item.spectacle.total;
          }
          if (item.type) {
              this.giftCardsTotal += item.totalPrice;
          }
      });
      this.total += this.giftCardsTotal;

    })

    setTimeout(() => this.cartService.initCart(), 100)

This code has been updated to address issues with the if statement and findIndex function not returning valid results.

Answer №1

In my opinion, what you are currently doing seems a bit excessive and the usage of findIndex appears to be incorrect. A simpler solution can be achieved by making some modifications to the code like so:

    this.cartItems.forEach(item => {
        const indexEmptyItem = !item.restaurant || !item.spectacle || !item.placesListContent || item.placesListContent < 1;
        const giftItemIndex = !item.type;
        this.disableBookBtn = (indexEmptyItem || giftItemIndex) ? true : false;
        // perform other actions based on each item
      })

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 arise when trying to access environment variables using react-native-dotenv in React

I am currently working on two separate projects, one being an app and the other a webapp. The app project is already set up with react-native-dotenv and is functioning as expected. However, when I attempt to use the same code for the webapp, I encounter an ...

Configuring the CKEditor edit functionality in Angular 2

If you're looking to configure your CKEditor in Angular2, you can refer to the documentation provided by CKEditor here. Here is an example of how I am using it in my HTML: <ckeditor [(ngModel)]="ckeditorContent" [config]="{toolbar : 'Bas ...

React Typescript: The element is implicitly assigned an 'any' type as the type does not have an index signature

While attempting to locate a key of an object using an item from an array, I encountered an error... An Element implicitly has an 'any' type because type lacks an index signature I've replicated the issue in this sandbox https://codesandbo ...

What is the best way to implement record updates in a nodejs CRUD application using prisma, express, and typescript?

Seeking to establish a basic API in node js using express and prisma. The schema includes the following model for clients: model Clients { id String @id @default(uuid()) email String @unique name String address String t ...

Displaying Pop Up Windows in Angular and Extracting Values from the Pop Up

When the Save Button is clicked, a PopUp should open triggering let dialogRef = this.dialog.open(this.callAPIDialog);. Inside the PopUp, I require a <textarea matInput placeholder="Leave a comment" formControlName="description"></textarea> and ...

Is the Inline Partial<T> object still throwing errors about a missing field?

I recently updated to TypeScript version ~3.1.6 and defined an interface called Shop as follows: export interface Shop { readonly displayName: string; name: string; city: string; } In this interface, the property displayName is set by the backend a ...

Is it possible to pass a different variable during the mouse down event when using Konva for 2D drawing?

I am trying to pass an additional value in a mouse event because my handleMouseDown function is located in another file. stage.on('mousedown', handleMouseDown(evt, stage)) Unfortunately, I encountered an error: - Argument of type 'void&apos ...

Leverage and implement a reusable class in Typescript

In a React Typescript project, I am facing a challenge. I want to utilize a base class component and add an additional property to its State. After attempting to modify the class from class ErrorBoundaryW extends PureComponent<any, State> {...} to ...

In Angular 2, how does the "this" keyword from the subscribe method reference the class?

I am using a subscription for Observable, and when it finishes I need it to call a function from this class. The issue is that the "this" keyword refers to the subscription and not to the class scope. Here is the code snippet: export class GoogleMapCompo ...

Can Angular tests be used to test a component that is a grandchild in the component hierarchy?

Currently, we are utilizing karma testing to verify the presence of buttons in a component. The challenge is that the component presents the buttons as children of another child. What we are examining is: ProductNavComponent \ NavComponent &bsol ...

Showcasing a single JSON object in an Angular application

After receiving a Json object from an API, I attempted to display it in my component with no success. Below is the code snippet of my component: selector: 'app-links-page-detail', templateUrl: './links-page-detail.component.html', ...

What is the reason behind hidden DOM elements appearing when I refresh the page?

When I refresh my webpage, I notice that the DOM elements I have hidden using ngIf are briefly visible before the actual state of my webpage loads. Why might this be happening? I am currently using Angular 8 version. <div *ngIf="!callInProgress ...

What is the best way to group/merge multiple objects that have the same name into a single object (Nesting)?

I have a dataset containing students' names and their marks in different subjects stored as an array of objects. My goal is to merge the data into a single object for each student with matching names, resulting in one record per student. Here is an ex ...

The depth buffer in Webgl FrameBuffer is not being cleared properly

Currently, I am working on developing a 2D sprite renderer that utilizes render textures for custom compositing. However, I have encountered an issue where the depth buffer on the FrameBuffer is not clearing properly. Due to this, all the sprites leave a p ...

Problems with importing modules in Apollo Server

I've encountered a never-ending stream of error messages post importing Apollo Server into my Typescript-based Node.js application. (Check out the screenshot below) It appears that Apollo is unable to locate anything in the graphql dependency. Could ...

Refreshing Components upon updates to session storage - Angular

Currently, I am in the process of developing a build-a-burger website using Angular. The ingredients and inventory need to be updated dynamically based on the selected location. Users can choose the location from a dropdown menu in the navigation bar. The ...

Error in Writing Functional Components with Typescript in React

I am struggling to create a versatile functional component and encountering issues like the one shown in this https://i.stack.imgur.com/WQkKg.png: Here is the code snippet: interface IAppTable<Type> { height: number; data: Type[]; tableLayout: ...

How can you partially update an entity in TypeORM using a query runner?

Updating a user's name partially is simple with the repository save method: await this.repository.save({ id: 1, name: 'john' }); However, when attempting to do the same using queryrunner, all fields must exist which throws an error stating ...

Is it possible to run Angular2 and Expressjs on separate ports?

I have set up my Angular2 application to use Expressjs as the backend. Both projects are structured within the same directory: /index.html <-- Angular index file /app.js <-- Expressjs /package.json /Gruntfile.js /bin <-- Expressjs bin ...

Using React Query's useMutation hook may result in an error message of "No overload matches this call"

When incorporating react-query into my typescript project, I encountered a perplexing type error while attempting to utilize the useMutation() hook with a graphql query. Here is an example of the code: useMutation( async ( parameter1: string, ...