我正在尝试从Rest API迁移到GraphQL,在服务器端使用Express + Mongoose,在客户端使用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
}
}`我如何在客户机上处理整个错误对象?
发布于 2017-09-07 03:58:34
当您进行突变时,Apollo客户端将返回一个承诺。可以在突变的结果promise的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)
);发布于 2019-03-02 02:10:20
您还可以在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;希望这能有所帮助!
https://stackoverflow.com/questions/45787299
复制相似问题