Warm tip: This article is reproduced from serverfault.com, please click

graphQL mutation error handling with React hooks(useMutation + Apollo-client)

发布于 2020-11-28 18:45:03

i cant show errors if login faild...

import React from 'react';
import {useMutation, gql} from '@apollo/client';

const LOGIN = gql`
    mutation login($userID: String!, $password: String!) {
        login(userID: $userID, password: $password) {
            id
            name
            theme
            lang
            userID
            token
        }
    }
`;

export default function Login() {
    const [state, setState] = React.useState({
           errorMessege: '',
           userID: '',
           password: '',
    });

    const [loginMutation] = useMutation(LOGIN, {
        update(proxy: any, result: any) {
            login(result.data.login);
        },
        variables: {
            userID: state.userID,
            password: state.password,
        },
    });


    return (
        <div>
           // show error here...
        </div>
    );
}

i don't know if i should use react-hooks because there was a different answer here:

Apollo client mutation error handling

it's working fine... but error handling is impossible.

Questioner
mamane man
Viewed
0
sina 2020-11-29 02:53:29

Actually it's ok...you just forgot to add onError!

const [loginMutation] = useMutation(LOGIN, {
        update(proxy: any, result: any) {
            login(result.data.login);
        },
        onError(err: any) {
            // err is for example: "Error: notFound"

            const error = `${err}`.split(':').reverse()[0];
            //this turns ' Error: notFound' to 'notFound'

            setState({
                ...state,
                modalMessege: `${error}`,
            });
        },
        variables: {
            userID: state.userID,
            password: state.password,
        },
    });