Apollo Integration
Apollo is a great solution for managing an application's data using GraphQL.
There are a few different implementation strategies for integrating Apollo and Curi based on how tightly you want them to be paired.
Setup
Apollo's React package provides an ApolloProvider
component for accessing your Apollo client throughout the application. The Router
(or whatever you name the root Curi component) should be a descendant of the ApolloProvider
because we don't need to re-render the ApolloProvider
for every new response.
Loose Pairing
Apollo and Curi don't actually have to know about each other. Curi can create a response without doing any data fetching and let Apollo handle that with its Query
component.
Any location data that a query needs can be taken from the response object. The best way to access this is to read the current response
from the context. This can either be done in the component or the response can be passed down from the root app.
Because we pass the response
to the route's body
component, we can pass a Query
the response's location params using props.response.params
.
Tight Pairing
You can use your Apollo client instance to call queries in a route's resolve
function. resolve
is expected to return a Promise, which is exactly what client.query
returns. Tightly pairing Curi and Apollo is mostly center around using resolve
to return a client.query
call. This will delay navigation until after a route's GraphQL data has been loaded by Apollo.
The external
option can be used when creating the router to make the Apollo client accessible from routes.
There are two strategies for doing this.
The first approach is to avoid the Query
altogether. Instead, you can use a route's response
property to attach the data fetched by Apollo directly to a response through its data
property.
While we know at this point that the query has executed, we should also check error
in the respond
function to ensure that the query was executed successfully.
When rendering, you can access the query data through the response
's data
property.
The second approach is to use the resolve
function as a way to cache the data, but also use Query
. With this approach, we do not have to attach the query data to the response; we are relying on the fact that Apollo will execute and cache the results prior to navigation.
The route's component will render a Query
to also call the query. Because the query has already been executed, Apollo will grab the data from its cache instead of re-sending a request to your server.
Prefetching
One additional benefit of adding queries to routes using resolve
is that you can prefetch data for a route.
The prefetch
interaction lets you programmatically fetch the data for a route prior to navigating to a location.