Home > Software design >  How to rewrite code into one using javascript and react?
How to rewrite code into one using javascript and react?

Time:02-11

i have two methods like below.

 const handleRowClick = React.useMemo(() =>
     !isRunning
         ? (itemId: string) => {
             startRun({items: [itemId] });
         }
         : undefined,
     [startRun]
 );

  const handleSelectedItemsClick = React.useMemo(() =>
      !isRunning
          ? (items: string[]) => startRun({ items: items })
          : undefined,
          startRun]
  );

  handleRowClick(itemId);
  handleSelectedItemsClick(itemIds);

as seen from above handleRowClick takes a string as an argument whereas handleSelectedItemsClick takes an array of strings as an argument.

how can I rewrite the above methods into one such that it can handle either a string or array of strings as input?

could someone help me with this? thanks.

CodePudding user response:

at function param set the the type string | string[]

the inside a function

(itemId: string | string[]) => {startRun({items: Array.isArray(itemId)?itemId:[itemId] });}

CodePudding user response:

const handleSelectedItemsClick = React.useMemo(() =>
    !isRunning
    ? (items: string[]) => startRun({ items: items })
    : undefined,
    [startRun]
);

const handleRowClick = (itemId) => {
    handleSelectedItemsClick([itemId]);
}

handleRowClick(itemId);
handleSelectedItemsClick(itemIds);
  • Related