DaCodeWiz
DaCodeWiz

Reputation: 115

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

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'.

Upvotes: 11

Views: 18031

Answers (2)

Ajay Gangarde
Ajay Gangarde

Reputation: 367

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

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202915

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>
  );
}

Upvotes: 30

Related Questions