5 javascript apollo reactjs graphql
我正在尝试在服务器上使用 Express + Mongoose 和在客户端上使用 React + Apollo 从 Rest API 转移到 GraphQL。
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
}
}`
Run Code Online (Sandbox Code Playgroud)
如何处理客户端上的整个错误对象?
当您进行更改时,Apollo 客户端会返回一个承诺。可以在突变的结果承诺的 catch 块中访问该承诺的错误。请参阅下面的示例。
如果我的登录突变有错误,我将在返回的承诺的 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)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1979 次 |
| 最近记录: |