Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Connect your API to a client


In the previous tutorials, we designed our database schema and got hocked up to a database and deployed our schema on Apollo Schema Manager.

In this section, we will focus exclusively on linking and connecting our graph API to a frontend with Apollo Client.

Apollo Client is a data management solution for Apollo. It was designed to be view-layer oriented, thus integrates with frontend frameworks like React, Vue, Angular, or even vanilla JS with ease.

While Apollo Client works with any view layer, it's most popular with React, maybe due to React popularity in the industry.

In the upcoming sections, we will be learning how to connect the API built in the previous section to a React application. It doesn't matter if you love Vue or Angular. The concepts are pretty much the same, and you would enjoy and follow along as we proceed.

Environment setup

For this part of the tutorial, our work will be in the client/ folder of our project. I assume that your project is at par with us, but if it's not, make sure to clone our project using this link. Then from the root of the project, run:

cd start/client && npm install

With the above command we have installed dependencies need to kick start our application. Here is a list of some of the packages we just installed:

  • apollo-client: A complete data management solution with built-in intelligent cache. This tutorial, uses the Apollo Client 3.0 preview since it includes local state management capabilities and sets up our cache up.
  • react-apollo: The view layer integration for React that exports the Query and Mutation components
  • graphql-tag: The tag function gql used for wrapping of query strings which enables them to be parsed into AST

Apollo VSCode Configuration

While Apollo VSCode is not required to successfully complete the tutorial, setting it up unlocks a lot of helpful features such as autocomplete for operations, jump to fragment definitions, and more.

First, duplicate the .env.example file located in client/ and call it .env. Add your Graph Manager API key that you already created in step #4 to this file:

ENGINE_API_KEY=service:<your-service-name>:<hash-from-apollo-engine>

The entry should basically look something like this:

ENGINE_API_KEY=service:my-service-439:E4VSTiXeFWaSSBgFWXOiSA

Our key is now stored under the environment variable ENGINE_API_KEY. Apollo VSCode uses this API key to pull down your schema from the registry.

Next, create an Apollo config file called apollo.config.js. This config file is how you configure both the Apollo VSCode extension and CLI. Paste the snippet below into the file:

module.exports = {
  client: {
    name: 'Space Explorer [web]',
    service: 'space-explorer',
  },
};

Great, we're all set up! Let's dive into building our first client.

Create an Apollo Client

Now that we have installed the necessary packages, let's create an ApolloClient instance.

Navigate to src/index.js so we can create our client. The uri that we pass in is the graph endpoint from the service you deployed in step 4.

If you didn't complete the server portion, you can use the uri from the code below. Otherwise, use your own deployment's URL, which may be different than the one below. Navigate to src/index.js and copy and paste the code below:

//src/index.js
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
const cache = new InMemoryCache();
const link = new HttpLink({
  uri: 'https://localhost:4000/'
});

const client = new ApolloClient({
  cache,
  link
});

In just a few lines of code, our client is ready to fetch data! Let's try making a query in the next section.

Make your first query

Before we show you how to use the React integration for Apollo, let's send a query with vanilla JavaScript.With a client.query() call, we can query our graph's API. Add the following line of code to your imports in src/index.js.

//src/index.js
import gql from "graphql-tag";

And add this code to the bottom of index.js:

//src/index.js
// ... above is the instantiation of the client object.
client
  .query({
    query: gql`
      query GetLaunch {
        launch(id: 56) {
          id
          mission {
            name
          }
        }
      }
    `
  })
  .then(result => console.log(result));

Open up your console and run npm start. This will compile your client app. Once it is finished, your browser should open to https://localhost:3000/ automatically. When the index page opens, open up your Developer Tools console and you should see an object with a data property containing the result of our query. You'll also see some other properties, like loading and networkStatus. This is because Apollo Client tracks the loading state of your query for you.

Apollo Client is designed to fetch graph data from any JavaScript frontend. No frameworks needed. However, there are view layer integrations for different frameworks that makes it easier to bind queries to the UI.

Go ahead and delete the client.query() call you just made and the gql import statement. Now, we'll connect our client to React.

Connect your client to React

Connecting Apollo Client to our React app with Apollo's hooks allows us to easily bind GraphQL operations to our UI.

To connect Apollo Client to React, we will wrap our app in the ApolloProvider component exported from the @apollo/react-hooks package and pass our client to the client prop. The ApolloProvider component is similar to React's context provider. It wraps your React app and places the client on the context, which allows you to access it from anywhere in your component tree.

Open src/index.js and add the following lines of code:

src/index.js
import {ApolloProvider} from '@apollo/react-hooks';
import React from 'react';
import ReactDOM from 'react-dom';
import Pages from './pages';
// previous variable declarations
ReactDOM.render(
  <ApolloProvider client={client}>
    <Pages />
  </ApolloProvider>, document.getElementById('root')
);

Now, we're ready to start building our first component with the useQuery hook in the next section.

Previous: Run your graph in production
Next: Fetch data with queries