How to run a mutation on mount with React Apollo 2.1's Mutation component? How to run a mutation on mount with React Apollo 2.1's Mutation component? reactjs reactjs

How to run a mutation on mount with React Apollo 2.1's Mutation component?


Right or wrong, Apollo makes some assumptions about how queries and mutations are used. By convention queries only fetch data while mutations, well, mutate data. Apollo takes that paradigm one step further and assumes that mutations will happen in response to some sort of action. So, like you observed, Query fetches the query on mount, while Mutation passes down a function to actually fetch the mutation.

In that sense, you've already deviated from how these components are "supposed to be used."

I don't think there's anything outright wrong with your approach -- assuming called never gets reset, your component should behave as intended. As an alternative, however, you could create a simple wrapper component to take advantage of componentDidMount:

class CallLogin extends React.Component {  componentDidMount() {    this.props.login()  }  render() {    // React 16    return this.props.children    // Old School :)    // return <div>{ this.props.children }</div>  }}export default function Authenticator({ apiKey, render }) {  return (    <Mutation mutation={AUTH_MUTATION} variables={{ apiKey }}>      {(login, { data, error }) => {        const token = (data && data.login.token) || undefined;        return (          <CallLogin login={login}>            {render({ error, token })}          </CallLogin>        )      }}    </Mutation>  );}


Here is my implementation for my slightly unique case and it works well:

const VERIFY_USER = gql`    mutation Verify_User($token: String!){        verifyUser(token:$token){            token        }    }`class Authenticator extends Component {  state = { redirect: false }  redirect = (authStatus) => {    this.setState({redirect:true}) }  render() {    if(this.redirect){      return <Redirect to="/" />    }    const { token } = this.props.match.params    console.log(token, "the token sir")    return (      <Mutation mutation={VERIFY_USER} variables={{ token }}>        {(mutation) => {          return (            <VerifyUser authenticateUser={mutation} redirect={this.redirect}/>          )        }}      </Mutation>    )  }}class VerifyUser extends Component {  componentDidMount(){    this.authUser();  }  authUser = async () => {    let userStatus = await this.props.authenticateUser() // call the mutation    this.props.redirect(userStatus)  }  render() {    return null  }}export default Authenticator