使用 React 钩子处理 graphQL 突变错误(useMutation + Apollo-client)

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

如果登录失败,我无法显示错误...

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>
    );
}

我不知道我是否应该使用 react-hooks 因为这里有不同的答案:

它工作正常...但无法进行错误处理。

其实没关系...你只是忘了添加 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,
        },
    });