Gergő Horváth
Gergő Horváth

Reputation: 3705

Component can't catch error from function passed as a prop

I have a Form component, and when the submit button is clicked, it calls:

//Form.js
    //...
    const submit = () => {
            try {
                onSubmit(values); //onSubmit from props, values from state
            } catch (error) {
                console.log(error);
                setSubmitError(error);
            }
    }
    //...

I'm trying to use it with onSubmit passed as:

export const signIn = ({ email, password }) => (
    auth()
    .signInWithEmailAndPassword(email, password)
    .catch(e => { throw e })
);

But it doesn't handle it. In the current version, it throws an error to the console: auth.esm.js:429 Uncaught The email address is badly formatted. I tried wrapping the error with new Error, but then it throws it to the window. What am I doing wrong?

Upvotes: 1

Views: 335

Answers (1)

jsdeveloper
jsdeveloper

Reputation: 4055

A normal try/catch block cannot catch async errors. However you can declare an async block and this should work:

const submit = async () => {
            try {
                await onSubmit(values); //onSubmit from props, values from state
            } catch (error) {
                console.log(error);
                setSubmitError(error);
            }
    }

Upvotes: 2

Related Questions