2

How can I handle errors for useMutation so the page doesn't turn into an unpleasant Unhandled Rejection (Error)?

While this post here describes my problem, I still couldn't solve it. The post especially mentions. Instead of having to write the above boilerplate yourself, you can just use the provided result object. I did that with:

const [signUp, { loading: mutationLoading, error: mutationError } [...]

However, my React App always switches to a not nice "Unhandled Rejection (Error): GraphQL error" screen when an error occurs. A similar solution seems to work in the official doc – but not for me.

function SignUp() {
  // Declare a new state variable, which we'll call "count"
  const [login, setLogin] = useState(true);
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [
    signUp,
    { loading: mutationLoading, error: mutationError }
  ] = useMutation(SIGNUP_MUTATION, {
    onCompleted(data) {
      const { token } = login ? data.tokenAuth : data.createUser;
      localStorage.setItem(AUTH_TOKEN, token);
      console.log(token);
      // this.props.history.push(`/`);
    }
  });

  return (
    <div>
      {mutationLoading && <p>Loading...</p>}
      {mutationError && (
        <p>
          Some error occured :(
          {console.log(mutationError)}
          {mutationError.graphQLErrors.map(({ message }, i) => (
            <span key={i}>{message}</span>
          ))}
        </p>
      )}
[...]
Joey Coder
  • 3,199
  • 8
  • 28
  • 60
  • I wrote: "**Having error state like this can be useful when you want your UI to reflect the fact there's an error**. For example, you might change the color of an element until the mutation runs without an error. Instead of having to write the above boilerplate yourself, you can just use the provided result object." – Daniel Rearden Feb 21 '20 at 00:02
  • The `error` object is exposed as a convenience for manipulating your UI. It's not a substitute for actually handling the error using 1) `catch` or 2) `onError` or 3) using ErrorLink and removing the errors from the response. – Daniel Rearden Feb 21 '20 at 00:05
  • Thank you for the answer Daniel. You you give me an example for my code with 1) I couldn't manage to create a working version with that example – Joey Coder Feb 21 '20 at 07:15
  • 1
    `signUp.catch(e => /* do something with the error */)` – Daniel Rearden Feb 21 '20 at 09:10

1 Answers1

0
const [
    signUp,
    { loading: mutationLoading}
  ] = useMutation(SIGNUP_MUTATION, {
    onCompleted(data) {
      const { token } = login ? data.tokenAuth : data.createUser;
      localStorage.setItem(AUTH_TOKEN, token);
      console.log(token);
      // this.props.history.push(`/`);
    },
   onError: (err) => {
      setError(err);
    // mutationError = err;
   }
  });
vipin goyal
  • 671
  • 11
  • 17