Delete element from the array upon removal from the AutoComplete component

I am facing a challenge with the Material UI AutoComplete component in my project. The issue arises when I try to update the state of the associateList after clearing a TextField. Additionally, I would appreciate any guidance on how to handle removing an associate from the associateOptions list when they are added or removed from the TextField. Despite my attempts, I encountered errors stating that the item was not found in the associateOptions.

import { Autocomplete, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField } from '@mui/material';
import React, { useState } from 'react';

const rows = [
  { processPath: 'Role 1', headcount: 2 },
  { processPath: 'Role 2', headcount: 1 },
  { processPath: 'Role 3', headcount: 3 },
  { processPath: 'Role 4', headcount: 2 },
  { processPath: 'Role 5', headcount: 2 },
];

export const EmployeesByPath: React.FC = () => {
  const associateOptions = ['john', 'kevin', 'sally', 'mark'];
  // const [associateOptions, setAssociateOptions] = useState<string[]>(['john', 'kevin', 'sally', 'mark']);
  const [associateList, setAssociateList] = useState<Record<string, string[] | undefined>>({});

  const getAssociatesByProcessPath = (processPath: string): string[] => {
    return associateList[processPath] ?? [];
  };

  //   const handleAssociateRemove = (processPath: string, associateIndex: number): void => {
  //     setAssociateList((prevAssociateList) => ({
  //       ...prevAssociateList,
  //       [processPath]: [...getAssociatesByProcessPath(processPath).filter((_, i) => i !== associateIndex)],
  //     }));
  //   };

  const handleSelection = (processPath: string, associateIndex: number, associate: string | null): void => {
    setAssociateList((prevAssociateList) => {
      const updatedAssociateList = getAssociatesByProcessPath(processPath);

      if (associate) {
        updatedAssociateList[associateIndex] = associate;
      } else {
        updatedAssociateList.filter((_, i) => i !== associateIndex);
      }

      return {
        ...prevAssociateList,
        [processPath]: updatedAssociateList,
      };
    });
  };

  console.log(associateList);

  return (
    <>
      <TableContainer component={Paper} sx={{ minWidth: 800 }}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Process Path</TableCell>
              <TableCell>Associate Login</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row, rowIndex) => (
              <TableRow
                key={rowIndex}
                sx={{
                  '&:last-child td, &:last-child th': { border: 0 },
                }}>
                <TableCell style={{ width: '35%' }}>{row.processPath}</TableCell>
                <TableCell style={{ width: '45%' }} component='th' scope='row'>
                  {[...Array(row.headcount)].map((_: undefined, index: number) => (
                    <Autocomplete
                      //   disablePortal
                      sx={{ maxWidth: '240px', marginBottom: 1 }}
                      key={`roles-${index}`}
                      id='employeesList'
                      options={associateOptions}
                      onChange={(__, associate) => handleSelection(row.processPath, index, associate)}
                      renderInput={(params) => <TextField {...params} label={`Select an associate`} variant='outlined' />}
                    />
                  ))}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </>
  );
};

Answer №1

It appears that you are looking to manage a list of associates for each process path and need to delete an associate once it is cleared from the Autocomplete feature. The handleSelection function provided has a small issue with the logic for removing an associate. Below is an updated version that correctly removes associates:

const handleSelection = (processPath: string, associateIndex: number, associate: string | null): void => {
  setAssociateList((prevAssociateList) => {
    const updatedAssociateList = [...getAssociatesByProcessPath(processPath)]; // Make a copy of the array

    if (associate !== null) {
      updatedAssociateList[associateIndex] = associate;
    } else {
      updatedAssociateList.splice(associateIndex, 1); // Delete the associate at associateIndex
    }

    return {
      ...prevAssociateList,
      [processPath]: updatedAssociateList,
    };
  });
};

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

Utilize Material-UI function by passing a function as an argument

I am currently using material UI in conjunction with React. I have a main component: import React, { Component } from 'react'; import CreateNewGarden from './CreateNewGarden'; const cookies = new Cookies(); class Dashboard extends Co ...

A step-by-step guide on incorporating MarkerClusterer into a google-map-react component

I am looking to integrate MarkerClusterer into my Google Map using a library or component. Here is a snippet of my current code. Can anyone provide guidance on how I can achieve this with the google-map-react library? Thank you. const handleApiLoaded = ({ ...

Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C". My TypeScript code showcases my di ...

When triggering the fireEvent.mouseOver event, it seems that document.createRange is not a valid

Having trouble using fireClick.mouseOver(tab) to test tooltip functionality on tab hover. Here's a snippet of the code: it('should handle change on hover of tab', () => { const {getByTestId, getByRole} = renderComponent('Dra ...

Executing the routing component prior to any other tasks

Having an issue where the ProductsService is fetching data from the server and storing it in an Array. The ProductsComponent serves as the parent component, while the ProductsListComponent and ProductListItemsComponent are its children components. The flow ...

Trigger function in a different child component on mouse up

Trying to call a function in a child component from another child component in ReactJS. Specifically, I want to trigger a function in another component when the 'mouseup' event happens. Here is an illustration of what I am attempting to achieve: ...

Eslint for Typescript in Vue is throwing an error with a message "Unexpected token, expecting ','. Make sure to

Whenever I attempted to utilize vue's type assertion, I kept encountering this eslint error. To illustrate, consider the following snippet: data: function () { return { sellerIdToListings: {} as any, // 'as' Unexpected to ...

Zod data structure featuring optional fields

Is there a more efficient way to define a Zod schema with nullable properties without repeating the nullable() method for each property? Currently, I have defined it as shown below: const MyObjectSchema = z .object({ p1: z.string().nullable(), p2 ...

Can JSS support creating variables similar to Sass?

Currently, I am developing a project in React and utilizing Material-ui with JSS for styling. In Sass, we have the ability to define variables like $color: rgb(255, 255, 255) for later use. I am curious if it is possible to implement variable usage simi ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

Partial button clickability issue

There is a puzzling error where the button in the 'red area' is not clickable, and I can't seem to figure out why. Below are images illustrating the issue: https://i.stack.imgur.com/aPfcR.png https://i.stack.imgur.com/v5knZ.png Upon reac ...

After running the command "npx/npm create-react-app hello" to create a react app, I received the following message

Whenever I try to execute this command for creating a React app: C:\WINDOWS\system32> npm i create-react-app -g hello I receive the following message in my cmd prompt: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf ...

Looking for a feature where users can easily update their profile using an interactive edit button

I'm currently working on a website project and one of the features I'm tackling is the user's profile page. My objective is to create an edit button within the page that allows the user to modify their name, username, email, and update their ...

Setting up cookies and sessions in an Electron application

Creating a cookie/session in my Electron app has been tricky for me. I attempted to use the default document.cookie method, but unfortunately it did not work. I have looked through the Cookie documentation, but have not been able to find information on ho ...

React - Incorrect use of hooks and class components

Understanding hooks as the opposite of a class component can be confusing. A simple line of code can trigger an error when trying to adapt it for use in a class component. Take, for example, this situation: .jsx files and functional components work seamles ...

Create a customized design for the Tiptap editor to mimic the appearance of a Material UI

Is there a way to customize the appearance of a Tiptap editor to match that of a Material-UI text field, particularly the outlined or standard variant? I'm looking for a solution to make the border of the Tiptap editor resemble that of a Material-UI t ...

What is the best method to retrieve the transloadit final link stored on a file's storage server (such as Google Cloud Storage) and bring it back to the component?

Trying to understand how to retrieve the final link stored in Google Storage (starting with "https://storage.googleapis.com/...") within a React component, but finding the documentation unclear. Even after successful file upload, I keep receiving "ASSEMBL ...

Tips for Invoking an Overloaded Function within a Generic Environment

Imagine having two interfaces that share some fields and another interface that serves as a superclass: interface IFirst { common: "A" | "B"; private_0: string; } interface ISecond { common: "C" | "D"; private_1: string; } interface ICommo ...

Stop webpack from stripping out the crypto module in the nodejs API

Working on a node-js API within an nx workspace, I encountered a challenge with using the core crypto node-js module. It seems like webpack might be stripping it out. The code snippet causing the issue is: crypto.getRandomValues(new Uint32Array(1))[0].toS ...

When incorporating <Suspense> in Next.js, the button's interaction was unexpectedly lost

'use client' import React, { Suspense } from "react"; const AsyncComponent = async () => { const data = await new Promise((r) => { setTimeout(() => { r('Detail'); }, 3000) }) as string; return <div>{d ...