0

Per the Apollo Docs, I'd like to get the mutate() function from ApolloClient into the props belonging to my react component. Is this the correct/preferred way to do it?

class myComponent extends React.Component {
    constructor(props) {
        super(props);
        this.mutate = props.client.mutate();
    };
}
VikR
  • 4,818
  • 8
  • 51
  • 96

1 Answers1

3

If you want to use the apollo client to call a mutation dynamically than you could use it like so:

import { withApollo } from 'react-apollo';

class myComponent extends React.Component {
  constructor(props) {
    super(props);
    this.mutate = props.client.mutate;
  }

  onClick = () => {
    this.mutate({
      mutation: gql `${<define your graphql mutation>}`,
      variables: { ... },
    }).then(...);
  }
  
  ...
}

export default withApollo(MyComponent);

Else i suggest you define your mutation statically with graphql and just call the mutation:

class MyComponent extends React.Component {
  onClick = () => {
    this.props.mutate({ variables: { ... } }).then(....);
  }

  ...

}

const yourGraphqlMutation = gql `${<define your graphql mutation>}`;

export default graphql(yourGraphqlMutation)(MyComponent);
Locco0_0
  • 3,420
  • 5
  • 30
  • 42