Was this helpful?

Connecting URQL

This guide will quickly setup a React single-page application using create-react-app, and configure it using URQL in order to send and receive data from the Alpaca Travel API

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

URQL is a highly customisable and versatile GraphQL client that is popular for its simple to advanced use. The aim is to create something lightweight, opposed to traditionally larger frameworks such as Apollo or Relay.

  • Lightweight and "blazingly" fast

  • Extensible at the core to support wider use cases

  • Effective caching

  • Great for a basic app, through to larger more complex projects

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 urql.

1npx create-react-app my-project --template @alpaca-travel/urql

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

Update your API Key

Modify the .env file and replace REACT_APP_ALPACA_ACCESS_TOKEN=... with your API 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

URQL is a single package that provides the same client for React, Preact and Svelte. The below is based on the urql quickstart.

  • urql: The main package we will be using

  • graphql: For working with our grapql queries

1npm install urql graphql
2# or
3yarn add urql graphql

Configuring the GraphQL Client

URQL 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 urql 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.

Creating the URQL Client

Create the new file src/client.js. We can then import createClient from urql and add the GraphQL endpoint to the url property of the options object.

1// src/client.js
2import { createClient } from "urql";
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 = createClient({
9  url: `${endpoint}?accessToken=${accessToken}`,
10});
11
12export default client;

Integrating into React

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

In your src/index.js, we will first import the Provider 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 { Provider } from "urql";
5import "./index.css";
6import App from "./App";
7import * as serviceWorker from "./serviceWorker";
8import client from "./client";
9
10ReactDOM.render(
11  <React.StrictMode>
12    <Provider value={client}>
13      <App />
14    </Provider>
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 } from "urql";
4
5const PLACE = /* GraphQL */ `
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 [result] = useQuery({
21    query: PLACE,
22    variables: { placeId: "place/facebook:place:370266736485353" },
23  });
24
25  const { data, fetching, error } = result;
26
27  if (fetching) return <p>Loading...</p>;
28  if (error) return <p>Oh no... {error.message}</p>;
29
30  return (
31    <div>
32      <h2>
33        When in Melbourne, go for a coffee at{` `}
34        <a href={data.place.contact.facebookUrl}>{data.place.name}</a> in{` `}
35        {data.place.address.locality} 🦙☕ 🚀
36      </h2>
37    </div>
38  );
39}
40
41export default App;

You are ready!

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

alpaca.tech

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