Home > OS >  Typescript error when using React updater functions to update state
Typescript error when using React updater functions to update state

Time:12-29

I'm setting a toggle with useState using updater functions to update the state.

https://beta.reactjs.org/reference/react/useState#updating-state-based-on-the-previous-state

I have this component

const [toggle, setToggle] = useState<boolean>(true);
...
<MyContainer handleToggle={setToggle}>
// MyContainer.tsx

type Props = {
  handleToggle: (value: boolean) => void;
};

export const MyContainer = ({handleToggle }: Props) => {
   ...
   // I call handleToggle this component like this
   handleToggle((prevState: boolean) => !prevState);
   ...
}

I'm getting this typescript error

(parameter) prevState: boolean
Argument of type '(prevState: boolean) => boolean' is not assignable to parameter of type 'boolean'.

How can I solve this?

CodePudding user response:

setToggle expects a boolean but you're passing a function that returns a boolean

try to change handleToggle(prevState => !prevState); to handleToggle(!toggle);

CodePudding user response:

It looks like the issue is with the type of the handleToggle function in the MyContainer component. The type of the handleToggle function is defined as (value: boolean) => void, but you are trying to pass a function that takes a boolean argument and returns a boolean. To fix this issue, you can update the type of the handleToggle function to (update: (prevState: boolean) => boolean) => void. This will allow you to pass the function that you are currently using to update the state.

type Props = {
  handleToggle: (update: (prevState: boolean) => boolean) => void;
};

export const MyContainer = ({handleToggle }: Props) => {
   ...
   // You can now call handleToggle with the updater function bro
   handleToggle((prevState: boolean) => !prevState);
   ...
}

  • Related