Type 'Dispatch<hook>' is not assignable to type '() => void'
Asked Answered
E

2

10

I tried looking through similiar questions and articles but nothing really seemed to work. I'm also somewhat at a loss as to what the error means since I tried to set a value and tried to declare a type but neither worked.

import React, { createContext, SetStateAction, useState } from 'react';

export const MenuContext = createContext({
    open: false,
    setOpen: () => {},
});
export default function MenuManager(props:any) {
    const [open, setOpen] = useState(false);
    return (
        <MenuContext.Provider value={{ open, setOpen }}>
            {props.children}
        </MenuContext.Provider>
    );
}

The error is gives back is

Type 'Dispatch<SetStateAction<boolean>>' is not assignable to type '() => void'.
Everglades answered 13/10, 2022 at 19:53 Comment(0)
P
29

Declare an interface for the MenuContext and correctly type the context and setOpen state updater function.

Example:

import React, { createContext, SetStateAction, useState, Dispatch } from 'react';

interface IMenuContext {
  open: boolean;
  setOpen: Dispatch<SetStateAction<boolean>>;
}

export const MenuContext = createContext<IMenuContext>({
  open: false,
  setOpen: () => {},
});

Also, instead of any you'll want to type the ManuManager component's props.

function MenuManager(props: React.PropsWithChildren<{}>) {
  const [open, setOpen] = useState(false);
  return (
    <MenuContext.Provider value={{ open, setOpen }}>
      {props.children}
    </MenuContext.Provider>
  );
}
Potemkin answered 13/10, 2022 at 20:5 Comment(1)
Drew you're very good at your job:DEverglades
S
0

type IProps = { deliveries: string[], selectedDelivery: string, handleDeliveryChange: (event: React.ChangeEvent) => void; // Assuming it's a select element }

Sworn answered 28/4, 2024 at 4:54 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.