Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.
like image 571
DaCodeWiz Avatar asked Mar 21 '26 00:03

DaCodeWiz


1 Answers

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>
  );
}
like image 163
Drew Reese Avatar answered Mar 23 '26 19:03

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!