簡體   English   中英

如何使用React-Apollo處理GraphQL錯誤?

[英]How to handle GraphQL errors with React-Apollo?

我正在嘗試使用Express + Mongoose在服務器上運行Rest API到GraphQL,在客戶端使用React + Apollo。

async resolve(_, { email, password, passwordConfirmation }) { // Sign Up mutation
            const user = new User({ email });
            user.password = password;
            user.passwordConfirmation = passwordConfirmation;
            try{
                const createdUser = await user.save();
                return createdUser;
            } catch(error) {
                console.log(error); // Returns errors object like {email: {message: 'E-mail is required'}}
                throw new Error(error); // But on the client there is a string with all errors
            }
        }`

如何處理客戶端上的整個錯誤對象?

當您進行突變時,Apollo客戶端會返回一個承諾。 可以在突變的結果承諾的catch塊中訪問該promise的錯誤。 請參閱下面的示例。

如果我的登錄變異有錯誤,我將在返回的promise的catch塊中訪問它們,然后將這些錯誤設置為組件中的本地狀態。 從那里可以呈現錯誤(如果存在),或者甚至可以傳遞給要呈現的子組件(如果您願意)。 請注意,錯誤通常以數組形式返回。

class LoginForm extends Component {
  constructor(props) {
    super(props);

    this.state = { errors: [] };
  }


  onSubmit({ email, password }) {
    this.props.mutate({
      variables: { email, password },
      refetchQueries: [{ query }]
    }).catch(res => {
      const errors = res.graphQLErrors.map(error => error.message);
      this.setState({ errors });
    });
  }

  render() {
    return (
      <div>
        <AuthForm
          errors={this.state.errors}
          onSubmit={this.onSubmit.bind(this)}
        />
      </div>
    );
  }
}

export default graphql(query)(
  graphql(mutation)(LoginForm)
);

您還可以在react-apollo中使用renderProps ,它會在第二個參數中的對象中提供錯誤和加載狀態。

import React, { Component } from 'react';
import { Mutation } from 'react-apollo';
import gql from 'graphql-tag';
import Error from './ErrorMessage';

const LOGIN_MUTATION = gql`
  mutation LOGIN_MUTATION($email: String!, $password: String!) {
    signin(email: $email, password: $password) {
      id
      email
      name
    }
  }
`;

class Login extends Component {
  state = {
    name: '',
    password: '',
    email: '',
  };
  saveToState = e => {
    this.setState({ [e.target.name]: e.target.value });
  };
  render() {
    return (
      <Mutation
        mutation={LOGIN_MUTATION}
        variables={this.state}
      >
        {(login, { error, loading }) => (
          <form
            method="post"
            onSubmit={async e => {
              e.preventDefault();
              await login();
              this.setState({ name: '', email: '', password: '' });
            }}
          >
            <fieldset disabled={loading}>
              <h2>Sign into your account</h2>
              <Error error={error} />
              <label htmlFor="email">
                Email
                <input
                  type="email"
                  name="email"
                  placeholder="email"
                  value={this.state.email}
                  onChange={this.saveToState}
                />
              </label>
              <label htmlFor="password">
                Password
                <input
                  type="password"
                  name="password"
                  placeholder="password"
                  value={this.state.password}
                  onChange={this.saveToState}
                />
              </label>

              <button type="submit">Sign In!</button>
            </fieldset>
          </form>
        )}
      </Mutation>
    );
  }
}

export default Login;

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM