0
votes

I have the following code which I am trying to decide how to handle errors:

const gqlWrapper = graphql(registerMutation, {
    props: ({ mutate, ownProps }) => ({
        registerUser: userDetails => {
            mutate({
                variables: { ...userDetails },
                update: (proxy, resp) => {
                    // perform update to local state based on success
                }
            }).catch(err => {
                console.log(err);
                // how to update components from here?
            });
        }
    })
});

export default gqlWrapper(Register);

The server sends back a GraphQL error object and sends this back so it appears in the catch() block of the mutation. If the mutation was successful, the component's data is updated using the proxy param, but I can't see an equivalent way of dealing with errors.

Ideally, I'd like to update the Apollo cache in the catch block, but I can't even inject props to the component or state at this point either.

The end result would be to set a prop/state on the Register component which shows an error message component with conditional rendering. One way could be to handle the error from where the registerUser mutation originates:

// Where the registerUser mutation get's initiated - on form submit
onSubmit={() => {
    this.props.registerUser(values);
    // the error could be caught here but I don't want this in the UI - I'd rather keep all this outside
}}

But I feel this adds bulk to the UI which I'd rather have at the bottom of the page, alongside the mutation function. What are the ways around this, or am I missing something obvious?

Thanks!

1

1 Answers

0
votes

Your best bet would be to use something like https://www.npmjs.com/package/apollo-link-error with your Apollo client. This would allow you to handle the errors and apply any custom logic you need based on those errors. It should allow you to keep .catch out of your components as well. In fact this module is recommended in Apollo's documentation