Home > Blockchain >  How to solve error when trying to implement hook
How to solve error when trying to implement hook

Time:04-08

I'm wanting to create a hook to place the states and event functions of my menus. But when I import the click function in this component, the following error appears:

"No overhead matches this call. The 1 of 2 overload, '(props: { slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ref?: ((instance: HTMLDivElement | null) => void) | RefObject< ...> | null | undefined; ... 251 more ...; onTransitionEndCapture?: TransitionEventHandler<...> | undefined; } & { ...; } & { ...; }): ReactElement<. ..>', generated the following error. The type 'boolean | (() => void)' cannot be assigned to type 'MouseEventHandler | Undefined'. Type 'boolean' cannot be assigned to type 'MouseEventHandler'."

How can I solve it?

  import { useState } from "react";


export const useMenu = () => {
    const [openCardOptions, setOpenCardOptions] = useState(false);

    const handleOpenCardOptions = () => {
      setOpenCardOptions(!openCardOptions);
    };

    return [openCardOptions, handleOpenCardOptions]
}
import { useMenu } from "../../hooks/useMenu";


export const NoteCard = () => {
  const [openCardOptions, handleOpenCardOptions] = useMenu()

  return (
    <Container>
      <TopBar>
        <ImgContainer>
          <img src={noteImg} alt="Note" />
        </ImgContainer>

        <Menu onClick={handleOpenCardOptions}>
          <img src={menuImg} alt="Menu" />

          {openCardOptions && (
            <CardOptions>
              <div>
                <img src={viewImg} alt="View" />
                <p>Visualizar</p>
              </div>

              <div>
                <img src={pencilImg} alt="Pencil" />
                <p>Editar</p>
              </div>

              <div>
                <img src={binImg} alt="Bin" />
                <p>Deletar</p>
              </div>
            </CardOptions>
          )}
        </Menu>

CodePudding user response:

Try changing the return statement of your function to

return [openCardOptions, handleOpenCardOptions] as const;

If you check the existing return type of useMenu(), you'll see it returns Array<boolean | (() => void)>--a variable array where every item can either be a boolean or a function. That's not what you're looking for though.

You instead want your return type to be a tuple, where the first item is always a boolean and the second item is always a function. as const tells TypeScript to treat array literals as tuples instead of arrays (among other things, noted here).

You could also explicitly write out the return type for useMenu if that makes more sense:

export const useMenu = (): [boolean, () => void] => {
  • Related