Now that we have created an
ApolloClient instance and attached it to our UI tree with
ApolloProvider, we can start using the main function of
react-apollo: adding GraphQL functionality to our UI components.
graphql container is the recommended approach for fetching data or making mutations. It is a Higher Order Component for providing Apollo data to a component, or attaching mutations.
The basic usage of
graphql is as follows:
If you are using ES2016 decorators, you may prefer the decorator syntax:
In this guide, we won’t use the decorator syntax to make the code more familiar, but you can always use it if you prefer.
graphql function takes two arguments:
query: Required, a GraphQL document parsed with the
config: An optional object with configuration, as described below
The config object can include one or more of the following keys:
name: Rename the prop the higher-order-component passes down to something else
options: Pass options about the query or mutation, documented in the queries and mutations guides
props: Modify the props before they are passed into the child component
withRef: Add a method to access the child component to the container, read more below
shouldResubscribe: A function which gets called with current props and next props when props change. The function should return true if the change requires the component to resubscribe.
graphql function returns another function, which takes any React component and returns a new React component class wrapped with the specified query. This is similar to how
connect works in Redux.
withApollo is a simple higher order component which provides direct access to your
ApolloClient instance as a prop to your wrapped component. This is useful if you want to do custom logic with apollo, such as calling one-off queries, without using the
If you need to get access to the instance of the wrapped component, you can use
withRef in the options.
This will allow a
getWrappedInstance method on the returned component which will return the wrapped instance.
react-apollo exports a
compose function. Adopting the following pattern allows you to reduce the number of reassignments you’re doing every time you wrap your component with
graphql and often