javascript - How to handle GraphQL errors with React-Apollo? -
i'm trying move rest api graphql using express + mongoose on server , react + apollo on client.
async resolve(_, { email, password, passwordconfirmation }) { // sign 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 {email: {message: 'e-mail required'}} throw new error(error); // on client there string errors } }`
how can handle whole object of errors on client?
the apollo client returns promise when make mutation. errors promise can accessed in catch block of mutation's resultant promise. see example below.
if there errors login mutation, access them in catch block of promise returned , set errors local state in component. there errors can rendered if exist, or passed down child component rendered if like. please note errors returned in array.
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) );
Comments
Post a Comment