Apollo Client is the best way to use GraphQL to build client applications.
With React Apollo, we can now easily manage own data just using components as well. Thinking in components is one of the many amazing things for me 👍
The client setup couldn’t be easier. 😃 We’ll initiate a client and give it the URI to our GraphQL server endpoint and then use the ApolloProvider component to to make the client available in our app’s components.
Let’s first import the necessary dependencies and create an ApolloСlient:
💡 A few things to note:
✔️ We initialize the client with an HttpLink that points to our GraphQL endpoint and then also specify Apollo’s InMemoryCache as the caching utility.
✔️ We use the ApolloProvider component, pass it our client as prop and then wrap it around our App component.
Now that everything’s in place, we can start running queries against the GraphQL endpoint.
For this, we’ll use React Apollo’s Query component, which makes use of the render proppattern to give us the data back from the query.
and let’s look at a few things that happened here:
️️ ✔️ React Apollo’s <Query /> component takes a required query prop with a GraphQL query that has been parsed using graphql-tag’s gql
(💡 query also takes a required children prop that should be a function.)
✔️ The data property holds the data received back from the query, the error property holds an error object, if any, and the loading property will be true while the query is in-flight.
⚛️ There you have it!
An easy way to get started with React and GraphQL and start running queries.
😃 If you have any questions, you can send them right now!