Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type async function passed as prop to React component

How should I type an async function that I'm passing to my React component as a property?

My component is defined below. Specifically I don't know how to type the addTask property in my interface:

interface INewTaskEntryProps {
    addTask:any; // this 
}
class NewTaskEntry extends React.Component<INewTaskEntryProps> {
    ...
    render() { 
        return (
            ...
            <button onClick={(e) => this.props.addTask(e)}>Do Something</button>
            ...
        );
    }
}

And my async function is defined like so:

const addTask = async (e) => {
    ...
    try {
        const newID = await mongoTaskCollection.insertOne({
            ...
        });
    }
    ...
}

And finally I pass the async function into my component like so:

<NewTaskEntry addTask={addTask} />
like image 453
codedude Avatar asked Jul 23 '26 02:07

codedude


1 Answers

Depending on what addTask returns but can be something like this:

interface INewTaskEntryProps {
  addTask: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => Promise<void>; 
}

In this case you are telling addTask returns a promise that resolve null value. If your fn returns the mongo document and you have it typed you can add that (like Promise<Task>) instead of void as the return value.

like image 131
Milton Avatar answered Jul 24 '26 22:07

Milton



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!