Was this helpful?

Connecting Apollo

_Note: This document is out of date and we recommend you referencing the topic of React Apollo Client_

This guide will quickly setup a React single-page application using create-react-app, and configure it using Apollo to connect to the Alpaca Travel API.

You can bypass the need for this tutorial now by reviewing the Alpaca GraphQL JavaScript SDK For React/Apollo which allows you to add capabilities to your existing applications.

Apollo is the industry-standard GraphQL implementation, proving the data graph layer that connects modern apps to the cloud. It is popular to use for its' ease of getting started, and that you can incrementally adopt features such as caching as you advance. The alternative fully-featured client is Relay offered by Facebook which offers an advanced environment but requires more learning.

  • Very popular with a lot of learning resources available

  • An ecosystem to offer solutions to a wide range of challenges

  • Backed by significant investment

  • Decent documentation

Getting Started

We've chosen to simplify the setup of a React application by using the Create React App project. This project is recommended by the React team for when you are learning React or creating a new single-page app. While it is quick to setup, it offers a reasonable toolset using the latest JavaScript features and provides a nice developer experience while optimising for production.

One line install

Using the below command, you will be up and running with a React application and a connection to the Alpaca Travel API through Apollo Boost.

This package uses:

  • Typescript (recommended)

  • Apollo Client

  • GraphQL Codegen (for generating types and hooks)

1npx create-react-app my-project --template @alpaca-travel/typescript-apollo-codegen

Note in the above, we are using npx which is not a typo. It is a package runner installed with npm 5.2+.

Refer to the documentation for help with this template.

Update your API Key

Create a .env file and replace REACT_APP_ALPACA_ACCESS_TOKEN=... with your API Key.

1REACT_APP_ALPACA_ACCESS_TOKEN=<your-api-public-key>

Start the development server

You can now start the React development server and launch your browser.

1npm start
2# or
3yarn start

For any issues starting your React application, refer to the Create React App Documentation.

Alternatively, add to an existing React App

You can add Apollo to your existing react application using the following:

  • @apollo/client: The main package we will be using

  • graphql: For working with our grapql queries

1npm install @apollo/client graphql
2# or
3yarn add @apollo/client graphql

Configuring the GraphQL Client

Apollo will be used as the client to connect to the Alpaca Travel API. All GraphQL clients send requests to a single "root endpoint" which is shown below. We will configure this into our app in the next section.

https://graphql.withalpaca.travel?accessToken=<YOUR_API_KEY>

Adding in the required environment variables

A preferred way of configuring the environment of your application is to use .env. If you have your own preferred way or your own security protocols to follow for managing environment variables, you can bypass this step and configure the apollo URI yourself.

Create a file in your project called .env with the following

1# .env
2REACT_APP_ALPACA_GRAPHQL_ENDPOINT=https://graphql.withalpaca.travel
3REACT_APP_ALPACA_ACCESS_TOKEN=<your-api-public-key>

Update the <your-api-public-key> section in the above with your API Key.

Info: You will need to restart the development server after changing .env files.

Warning: Generally, .env files should be checked in to source control with the exclusion of .env.local or .env.production.

For more information on managing environment variables see Create React App's Adding Custom Environment Variables.

Configuring ApolloClient

Create the new file src/client.js. We can then import ApolloClient from apollo-boost and add the GraphQL endpoint to the uri property of the options object.

1// src/client.js
2import { ApolloClient, InMemoryCache } from "@apollo/client";
3
4// Access the environment variables to configure the URI
5const endpoint = process.env.REACT_APP_ALPACA_GRAPHQL_ENDPOINT;
6const accessToken = process.env.REACT_APP_ALPACA_ACCESS_TOKEN;
7
8const client = new ApolloClient({
9  uri: `${endpoint}?accessToken=${accessToken}`,
10  cache: new InMemoryCache(),
11});
12
13export default client;

Integrating into React

Now that we have our environment setup with a client.js file exporting the apollo client, we can integrate the client into React.

In your src/index.js, we will first import the ApolloProvider which will provide the client through context to your React application and hooks and the provide it our configured client.

1// src/index.js
2import React from "react";
3import ReactDOM from "react-dom";
4import { ApolloProvider } from "@apollo/client";
5import "./index.css";
6import App from "./App";
7import * as serviceWorker from "./serviceWorker";
8import client from "./client";
9
10ReactDOM.render(
11  <React.StrictMode>
12    <ApolloProvider client={client}>
13      <App />
14    </ApolloProvider>
15  </React.StrictMode>,
16  document.getElementById("root")
17);
18
19// If you want your app to work offline and load faster, you can change
20// unregister() to register() below. Note this comes with some pitfalls.
21// Learn more about service workers: https://bit.ly/CRA-PWA
22serviceWorker.unregister();

An example query

We can now run a query in a React Component and start querying the API for data.

1// src/App.js
2import React from "react";
3import { useQuery, gql } from "@apollo/client";
4
5const PLACE = gql`
6  query getPlace($placeId: ID!) {
7    place(id: $placeId) {
8      name
9      contact {
10        facebookUrl
11      }
12      address {
13        locality
14      }
15    }
16  }
17`;
18
19function App() {
20  const { loading, error, data } = useQuery(PLACE, {
21    variables: { placeId: "place/facebook:place:370266736485353" },
22  });
23
24  if (loading) return <p>Loading...</p>;
25  if (error) return <p>Error :(</p>;
26
27  return (
28    <div>
29      <h2>
30        When in Melbourne, go for a coffee at{` `}
31        <a href={data.place.contact.facebookUrl}>{data.place.name}</a> in{` `}
32        {data.place.address.locality} 🦙☕ 🚀
33      </h2>
34    </div>
35  );
36}
37
38export default App;

You are ready!

You've now got a working React application configured to send requests to the Alpaca Travel API using Apollo Boost.

alpaca.tech

Copyright © 2023 - Made with love ❤️ in Australia.