Evanss
Evanss

Reputation: 23563

this not working in async function in React component

In my React component this.login() isn't executing. I believe this is because an await function changes the context of this, but I'm not sure how to fix it.

           await this.props
                .SignupUser({
                    variables: {
                        email: this.state.email,
                        password: this.state.password,
                        name: this.state.name,
                    },
                })
                .then(() => {
                    this.login();
                })
                .catch(error => {
                    this.setState({ wait: false });
                    const errorMessage = error.graphQLErrors[0].functionError;
                    this.setState({ error: errorMessage });
                });

Upvotes: 0

Views: 51

Answers (1)

Raja Jaganathan
Raja Jaganathan

Reputation: 36117

Remove await keyword, It should work.

Alternatively, we need to implement in a different way

The function must add async keyword in the function declaration for below code

 await this.props
    .SignupUser({
        variables: {
            email: this.state.email,
            password: this.state.password,
            name: this.state.name,
        },
    })
    .then(() => {
        this.login();
    })
    .catch(error => {
        this.setState({ wait: false });
        const errorMessage = error.graphQLErrors[0].functionError;
        this.setState({ error: errorMessage });
    });

(or)

    try {
    const user = await this.props
        .SignupUser({
            variables: {
                email: this.state.email,
                password: this.state.password,
                name: this.state.name,
            },
        });
    this.login();
} catch (e) {
    this.setState({ wait: false });
    const errorMessage = error.graphQLErrors[0].functionError;
    this.setState({ error: errorMessage });
}

Upvotes: 1

Related Questions