TheoG
TheoG

Reputation: 1558

HowTo: Access client.mutate method from Apollo? Refactoring from 1.9.2 to 2.4.2

OS: Windows 10 Pro
apollo-boost: "^0.1.16"
apollo-client: "^2.4.2"

Does anyone know how to access the client.mutate method from Apollo now? I wish to do the following:

  client.mutate({
      mutation: REMOVE_FROM_CART_MUTATION,
      variables: {
         cartItem.id,
      },
  })
  .catch(this.handleSubmitError);

....
withApollo(CartItem);

Upvotes: 0

Views: 281

Answers (1)

chris
chris

Reputation: 3321

If you're using React, you can import withApollo like so:

import { withApollo } from 'react-apollo';

then make sure to wrap the component (I do this on export):

export default withApollo(CartItem);

By doing so, ApolloProvider will automatically inject the client to your props and you can access it from within the component by doing this.props.client.mutate(...); or this.props.client.query(...);

NOTE: this means your component must be a child of the ApolloProvider in your component tree. The Apollo docs recommend doing this at the highest level possible in your App, such as:

<ApolloProvider client={client}>
  <App />
</ApolloProvider>

You can find more information on using the query and mutate APIs in the Apollo API client reference.

If you're trying to interact directly with your local cache, you can find information on the client.readyQuery() and client.writeQuery() APIs in the Apollo client GitHub repo.

Upvotes: 1

Related Questions