繁体   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