Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. Use it to fetch, cache, and modify application data, all while automatically updating your UI.
npm install @apollo/client graphql --save
@apollo/client: This single package contains virtually everything you need to set up Apollo Client. It includes the in-memory cache, local state management, error handling, and a React-based view layer.graphql: This package provides logic for parsing GraphQL queries.index.js, let's import ApolloClient from @apollo/client and provide our GraphQL server's URL as the uri property of the constructor's configuration object:// index.js
import React from "react";
import ReactDOM from "react-dom";
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://48p1r2roz4.sse.codesandbox.io', // Backend API address
cache: new InMemoryCache()
});
Connect Apollo Client to React with the ApolloProvider component.
The ApolloProvider is similar to React's Context.Provider.
It wraps your React app and places the client on the context, which enables you to access it from anywhere in your component tree.
In index.js, let's wrap our React app with an ApolloProvider.
We suggest putting the ApolloProvider somewhere high in your app, above any component that might need to access GraphQL data.
For example, it could be outside of your root route component if you're using React Router.
// index.js
import React from "react";
import ReactDOM from "react-dom";
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import Routes from "./Routes";
const client = new ApolloClient({
uri: 'https://48p1r2roz4.sse.codesandbox.io', // Backend API address
cache: new InMemoryCache()
});
ReactDOM.render(
<ApolloProvider client={client}>
<Routes />
</ApolloProvider>,
document.getElementById("root")
);
useQuery. useQuery is a React hook that use the Hooks API to share GraphQL data with your UI.gql function) to the useQuery hook. useQuery hook runs, a result object is returned that contains loading, error, and data properties:loading and error properties.data property.Update data with the useMutation hook
useMutation hook. useMutation React hook is the primary API for executing mutations in an Apollo application. useMutation within a React component and pass it a GraphQL string that represents the mutation. useMutation returns a tuple that includes: