Apollo Client (React)¶
Overview¶
You can use Apollo Client to connect to your Realm app's exposed GraphQL API from a React application. Apollo Client runs queries and mutations, maintains a client-side data cache, and integrates into your app with idiomatic React components and hooks.
Check out the MongoDB Realm GraphQL - Apollo (React) repository on GitHub to see
a fully set-up React & Apollo application that's ready to connect to your own
MongoDB Realm app. It uses the sample_mflix.movies
collection that's
included in the MongoDB Atlas sample data sets.
If you don't want to clone the repository, the demo application is also available in-browser in the Realm GraphQL CodeSandbox.
Set Up Apollo Client¶
Install Dependencies¶
As in any MongoDB Realm project, you'll need to install the Realm Web SDK to authenticate users and requests.
npm install realm-web
Apollo bundles the core components that you need to create a client in a package called @apollo/client. It also requires the graphql package to parse GraphQL queries.
npm install @apollo/client graphql
Create an Apollo GraphQL Client¶
Create a new ApolloClient object that points to your Realm app's GraphQL API endpoint. You generate the endpoint URL based on your Realm App ID or find it on the GraphQL page of the Realm UI.
import * as Realm from "realm-web"; import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client"; export const APP_ID = "<Your App ID>"; const graphql_url = `https://realm.mongodb.com/api/client/v2.0/app/${APP_ID}/graphql`; const client = new ApolloClient({ link: new HttpLink({ uri: graphql_url }), cache: new InMemoryCache(), });
Set Up User Authentication¶
The ApolloClient
is configured to send requests to your app. However, all
Realm GraphQL requests must include a valid user access token to authenticate
requests, so right now any operations sent from Apollo will fail.
To authenticate requests, you need to add an Authorization header with a valid Realm user access token to each GraphQL request.
You can authenticate a user and get their access token with the Realm
Web SDK. The Apollo HttpLink
object allows you to add custom
headers to every request by defining a custom fetch
function.
// Connect to your MongoDB Realm app const app = new Realm.App(APP_ID); // Get a valid Realm user access token to authenticate requests async function getValidAccessToken() { if (!app.currentUser) { // If no user is logged in, log in an anonymous user await app.logIn(Realm.Credentials.anonymous()); } else { // The logged in user's access token might be stale, // Refreshing custom data also refreshes the access token await app.currentUser.refreshCustomData(); } // Get a valid access token for the current user return app.currentUser.accessToken; } const client = new ApolloClient({ link: new HttpLink({ uri: graphql_url, fetch: async (uri, options) => { const accessToken = await getValidAccessToken(); options.headers.Authorization = `Bearer ${accessToken}`; return fetch(uri, options); }, }), cache: new InMemoryCache() });
Add the Apollo Client to Your App¶
The Apollo client
object is now configured to send authenticated GraphQL
requests to your MongoDB Realm app. All that's left to do is make it available
to the rest of your React application.
The @apollo/client
package exports an ApolloProvider
component that
makes the client
available to any Apollo hooks that you call from child
components. Wrap your app in an ApolloProvider
and pass the client
object to the provider.
import React from "react"; import { render } from "react-dom"; import App from "./App"; import { ApolloProvider, ApolloClient, HttpLink, InMemoryCache } from "@apollo/client"; // ... code to create the GraphQL client render( <ApolloProvider client={client}>
<App />
</ApolloProvider>, document.getElementById("root"), );
Run Queries and Mutations¶
The @apollo/client
package includes a set of declarative React hooks that
connect your components to the GraphQL API and handle query and mutation
execution.
To define queries and mutations that you can pass to the hooks, install graphql-tag:
npm install graphql-tag
Components that call the query and mutation hooks must be descendants of the
ApolloProvider that
you configured for your MongoDB Realm app. The hooks call the query and mutation methods on the
provided client
object.
Run a Query¶
Apollo Client includes two hooks for executing queries. The hooks accept identical parameters but differ in when they execute the query:
- useQuery() runs automatically when its component mounts. It also returns a callback that re-runs the query whenever you call it.
- useLazyQuery() returns a callback function that executes the query whenever you call it. It does not run the query on component mount.
Both hooks accept a query definition and additional options, including
variables
that Apollo passes to the query. They also both return information
about the query's current execution status and data returned from the most
recent execution.
import React from "react"; import { useQuery } from "@apollo/client"; import gql from "graphql-tag"; import MovieList from "./MovieList" // Must be rendered inside of an ApolloProvider export default function Movies() { const { loading, error, data } = useQuery(gql`
query AllMovies {
movies {
_id
title
year
runtime
}
}
`); if(loading) { return <div>loading</div> } if(error) { return <div>encountered an error: {error}</div> } return <MovieList movies={data.movies} /> }
Run a Mutation¶
The useMutation() hook
accepts a mutation definition and an optional configuration object. The most
common option you'll need to pass is a variables
object that maps to
GraphQL variables in the mutation
definition.
The hook returns several objects in an array:
- a callback function that executes the mutation
- an object that includes information on the mutation's execution status and data returned from the most recent execution.
import React from "react"; import { useMutation } from "@apollo/client"; import gql from "graphql-tag"; // Must be rendered inside of an ApolloProvider export default function MovieList({ movies }) { const [updateMovieTitle] = useMutation(gql`
mutation UpdateMovieTitle($oldTitle: String!, $newTitle: String!) {
updateOneMovie(query: { title: $oldTitle }, set: { title: $newTitle }) {
title
year
}
}
`); return ( <ul>
{movies.map((movie) => (
<li key={movie._id}>
<div>{movie.name}</div>
<button
onClick={() =>
updateMovieTitle({
variables: {
oldTitle: movie.title,
newTitle: "Some New Title",
},
})
}
>
Update Title
</button>
</li>
))}
</ul> ); }