Apollo-client: Question: Can i access mutation instance inside class functions with <Mutation /> tag?

Created on 30 Jul 2018  路  3Comments  路  Source: apollographql/apollo-client

Hi, I want to use Mutation with render props and need to access mutate function inside the class function

class C extends Component {
   login = (data) => {
      // need to access mutate function here!
   }

   render () {
    <Mutation 
        mutation={MUTATION}
        update={update}
    >
    {(mutate) => this.props.children(login)}
    </Mutation>
  }
}

is it possible?

Most helpful comment

Thanks a lot :+1:

All 3 comments

There are multiple options:

Using a wrapper component:

import React, { Component } from "react";
import { Mutation } from "react-apollo";

class InnerComponent extends Component {
  login = (data) => {
    this.props.mutate()
  }
  render() {
    return <LoginForm />
  }
}

class WrapperComponent extends Component {
  render() {
    return <Mutation {...mutationProps}>{mutate => <InnerComponent mutate={mutate} />}
  }
}

You can also create a higher order component factory:

import React, { Component } from "react";
import { Mutation } from "react-apollo";

function withMyMutation(WrappedComponent) {
  return function MutationWrapper(props) {
    return <Mutation {...mutationProps}>{mutate => <WrappedComponent {...props} mutate={mutate} />}</Mutation>
  }
}

const C = withMyMutation(
  class extends Component {
    login = (data) => {
      this.props.mutate()
    }
  }
  render() {
    return <LoginForm />
  }
)

Last but not least there is also the graphql HoC which is AFAIK deprecated. The documentation about that Component is not available anymore.

Thanks a lot :+1:

you can wrap your component with withApollo
import { withApollo } from 'react-apollo';

Was this page helpful?
0 / 5 - 0 ratings