4

I am trying to implement email verification system in react-apollo application and running into an issue. The problem is that I want to fire a GraphQL mutation on page load when a user visits a link with a verification token. The mutation currently is fired on a button click, but I want it to happen on page load.

I tried to return the mutation from render but it sent the application into an infinite loop.

return (
            <Mutation
              mutation={VERIFY_EMAIL_MUTATION}
              variables={{ id }}
              onCompleted={() => this.setState({ userVerified: true })}
            >
              {(verifyEmail, { loading, error }) => {
                 verifyEmail();
            }
            </Mutation>

How can I implement firing this mutation on page load?

turisap
  • 231
  • 4
  • 13
  • Consider using reac-apollo's graphql() and compose() functions instead of Mutation component or Query Component. Check them out [here](https://www.apollographql.com/docs/react/api/react-apollo/#graphqlquery-configcomponent) – Caleb Rotich Jun 04 '19 at 15:56

2 Answers2

1

Use compose and pass it down as a function to your component. The following method allows you to pass multiple mutations/queries, you can use them where-ever you want without and with triggers.

import React from "react";
import { compose, graphql } from "react-apollo";

import {
  VERIFY_EMAIL_MUTATION
} from "../GraphqlQueries/ServerQueries";

class YourComponent extends React.Component {
  componentWillMount() {
    this.props.verifyEmail({variables: {email: "your_email", variable2: "variable2" }});
  }

  render() {
    return (
      <React.Fragment>
        Your Render
      </React.Fragment>
    );
  }
}

export default compose(
  graphql(VERIFY_EMAIL_MUTATION, {
    name: "verifyEmail"
  })
)(YourComponent);
Avanthika
  • 3,984
  • 1
  • 12
  • 19
  • compose() is no longer available in react-apollo 3. Some solutions here https://stackoverflow.com/questions/57445294/compose-not-exported-from-react-apollo – josef Jan 17 '21 at 20:21
0

Rather than compose you can do it like this

 useEffect(() => {
        MutationName({
            variables: {
                variable1: variable1Value
            }
        });
    }, []);

useEffect behave as on pageload.

Abbas
  • 763
  • 1
  • 12
  • 26