Steps to display a modal dialog depending on the category of the label

I'm encountering an issue where clicking on different labels should show corresponding modal dialogs, but it always displays the same modal dialog for both labels ("All Recommendations"). Can anyone offer guidance on how to resolve this problem? Thank you in advance.

const ExportTypes: Array<{ label: string; id: string }> = [
 { label: 'All Recommendations', id: 'AllRecommendations' },
 { label: 'Entities By type', id: 'EntitiesBytype' },  
];

const handleModalExport = useCallback(
() => {
  if (ExportTypes.some(e => e.id === 'AllRecommendations')) {
      openModalDialog({
        title: t('Export all recommendations'),
        renderContent: () => <RecommendationExportModel />,
      });
    }
   else if(ExportTypes.some(e => e.id === 'EntitiesBytype')) { 
      openModalDialog({
        title: t('Export all'),
        renderContent: () => <RecommendationExportEntitiesModel />,
      });
    }
  },
 [openModalDialog, t],
);

{ExportTypes.map((objType) => (
  <MenuItem key={objType.id} onClick={handleModalExport}>
     {t(objType.label)}
  </MenuItem>
))}
 

Answer №1

The some() method evaluates whether at least one element in the array satisfies the condition specified by the provided function. It returns true if any element in the array meets the condition set by the function; otherwise, it returns false. The original array remains unchanged.

In this scenario, when you execute the handleModalExport() function, it is verifying the presence of an item with an id matching AllRecommendations within your ExportTypes constant. Since that specific item is always present, clicking on the MenuItem will consistently trigger the first conditional statement due to the fixed nature of the item id in your constant.

The main issue lies in not utilizing the id of the clicked item. To resolve this, ensure that the MenuItem passes the respective id of the clicked item for validation purposes.

You can rectify this by implementing the following:

<MenuItem key={objType.id} onClick={() => handleModalExport(objType.id})}>

Subsequently, update your callback function to utilize the dynamically passed id from the onClick event:

const handleModalExport = useCallback(
(id) => {
  switch (id) {
    case 'AllRecommendations':
      openModalDialog({
          title: t('Export all recommendations'),
          renderContent: () => <RecommendationExportModel />,
        });
      }
    break;
    case 'EntitiesBytype':
      openModalDialog({
        title: t('Export all'),
        renderContent: () => <RecommendationExportEntitiesModel />,
      });
    break;
    default:
      // handle this, throw? do nothing?
  },
 [openModalDialog, t],
);

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

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

Angular Form customizable field

I'm trying to figure out how to create an angular form with a dynamic step. Currently, my form in TypeScript looks like this: this.registerForm = new FormGroup({ role: new FormControl('', [ Validators.required, ]), firstName: ...

React-router-dom TypeScript error when defining the type of the prop parameter in the loader

I'm having trouble with the params prop in the loader prop within the routes. I've defined the params in TypeScript, but I'm getting errors that I don't understand. Any help would be appreciated, thanks in advance. I tried to use the Cu ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Tips on updating TypeScript to a higher major version

Despite upgrading all packages, deleting node_modules and package-lock.json, and reinstalling with npm install, the typescript runtime in my git repo is still showing version 4.9.5. How can I update the tsc version to be higher than 5.0? $ npx tsc --versi ...

"Encountering issues with importing Splitpanes while using VueJs and TypeScript combination

My VueJS view was originally written in JavaScript using the component "splitpanes" from npm package. The code was functioning well with the following structure: <template> <div> <Splitpanes :dbl-click-splitter="false" :horizont ...

Starting a nested JSON structure with TypeScript and Angular 7

I'm encountering an error when attempting to make a POST request by sending an object TypeError: Can not set property 'ItemCode' of undefined My setup involves Angular 7 and Typescript Here is my initial JSON: objEnvio:any = <an ...

Using Angular 2: Applying a specific class to a single element with [ngClass]

I have a header table with arrows indicating sorting order, using Bootstrap icons. However, when I click on a column, all columns receive the icon class. Here is an example of what I mean: https://i.sstatic.net/CAS81.png Below is the code snippet: HTML ...

A guide to implementing vue-i18n in Vue class components

Take a look at this code snippet: import Vue from 'vue' import Component from 'vue-class-component' @Component export default class SomeComponent extends Vue { public someText = this.$t('some.key') } An error is being thr ...

Ensuring the safety of generic types in Typescript

Typescript is known for its structured typing, which is a result of the dynamic nature of Javascript. This means that features like generics are not the same as in other languages with nominal type systems. So, how can we enforce type safety with generics, ...

What is the best way to limit the types of function parameters in TypeScript based on whether the parameter index is even or odd?

My goal is to create a function with an unlimited number of parameters, where the type of each parameter is determined by whether its index is odd or even. For example: flow(isMachineReady(), 'and', isWaterHot(), 'or', isMilkHot(), &ap ...

Implementing a global provider in Ionic 3

I have integrated a provider in my app that needs to stay active at all times while the application is running to monitor the network connection status. Following this guide, I included the class in my app.module.ts file to ensure it functions as a global ...

Refresh the content of an Angular modal with updated data each time the modal is launched

Currently, I am working on an angular web project that involves a main component class loading a Modal to update a report. Within this Modal, there are tabs - one of which is the transaction tab for which I am responsible. However, I have encountered an is ...

Discussing recursive types A <--> B with generics in TypeScript

I'm currently working with the following TypeScript code: type DormNodePredicate = DormEdge | (() => DormNode<DormNodePredicateRecord>); interface DormNodePredicateRecord { [key: string]: DormNodePredicate; } export class DormNode<DNPR ...

Issue arising with data exchange between components using data service in Angular 5

Utilizing data service to share information between components has presented a challenge for me. References: Angular: Updating UI from child component to parent component Methods for Sharing Data Between Angular Components Despite attempting the logic o ...

Why does the Amazon DynamoDB scan trigger an error by making two HTTP requests to the server?

My TypeScript React application is using DynamoDB services to store data, with a JavaScript middleware handling the database access operations. While developing locally, I successfully implemented the scan, put, and delete operations with no errors. Howeve ...

Using the keyof operator to determine the data type of a property within a TypeScript class

According to TypeScript's documentation on the keyof operator, you can access a property of an object instance using this function below. function getProperty<T, K extends keyof T>(o: T, name: K) { return o[name]; } If you want to obtain th ...

Rendering a component in React based on multiple conditions

Checking sessionStorage and another state variable before rendering a component is essential for my application. I want to avoid showing the same message multiple times within the same session. This is how I have implemented it: const addSession = (noteId: ...

I am experiencing issues with my Jest unit test case for Material UI's multi select component failing

I've been working on writing a unit test case for the material UI multi select component. The code for the parent component is as follows: import {myData} from '../constant'; export const Parent = () => { const onChangeStatus= (sel ...