WebArtisan
WebArtisan

Reputation: 4227

React hooks - exported method returns as boolean

I have a simple custom hook, for some toggle functionality:

import { useState } from 'react';

function useDialog(initialState: boolean) {
    const [isOpen, toggleDialog] = useState<boolean>(initialState);

    const open = () => {
        toggleDialog(true);
    };

    const close = () => {
        toggleDialog(false);
    };

    return [isOpen, open, close];
}

export default useDialog;

and I try to reuse it inside some component:

const SomeDialog = (props: any) => {
    const [isOpen, open, close] = useDialog(false);

    console.log('open :>> ', typeof open); // here is function type

    return (
        <div>
            <button onClick={open}>open</button> // ERRROR! -> Type 'false' is not assignable
        </div>
    );
};

export { SomeDialog };

Why error happend on onClick? Type 'false' is not assignable and how to properly fix it?

Upvotes: 0

Views: 1068

Answers (2)

Moshe Sommers
Moshe Sommers

Reputation: 1516

You need to add the typing to you're custom hook like so

function useDialog(initialState: boolean):[boolean,() => void,() => void] {
    const [isOpen, toggleDialog] = useState<boolean>(initialState);

    const open = () => {
        toggleDialog(true);
    };

    const close = () => {
        toggleDialog(false);
    };

   return [isOpen, open, close];
}  

Upvotes: 1

Dennis Vash
Dennis Vash

Reputation: 53994

Try typing the function instead of the value.

type Hook = (initialState: boolean) => [boolean, () => void, () => void];

const useDialog: Hook = initialState => {...}

Without it, open is referred with boolean | (() => void) type, which is not compatible with onClick of type React.MouseEvent.

Edit affectionate-gauss-vmef0

Upvotes: 1

Related Questions