Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Querying a GraphQL API in a React Web Application

TwitterFacebookRedditLinkedInHacker News

GraphQL is becoming all the rage, what with being able to query an API like you can query a database. There are two aspects when it comes to GraphQL development, the first being around creating GraphQL APIs and the other around creating applications that can query those APIs.

If you’ve been keeping up, you’re probably already familiar with my courses, Web Services for the Go Developer, and Web Services for the JavaScript Developer. In these courses we saw how to create a GraphQL API. Looking at things in the other direction, you might remember my tutorials, Query a GraphQL API on Android and iOS with NativeScript and Angular, and Query A GraphQL API with Vue.js and Axios, which demonstrated how to query a GraphQL in an Angular or Vue.js application.

This time around we’re going to explore another popular framework. We’re going to see how to query a GraphQL API from within a React application using a variation of methods.

The assumption is that you already have a GraphQL API to work with. If you don’t already have an API, this tutorial won’t teach you how to create one. We’re only going to explore interacting with an API.

Creating a New React Web Application with Boilerplate Code

To keep things easy to understand, we’re going to create a new project and work our way up. We’re not going to worry about creating any components, or doing anything above and beyond interacting with a GraphQL API.

From the command line, execute the following command:

npx create-react-app graphql-example

For this project we’re going to do all of our work in the project’s src/App.js file. Open the project’s src/App.js file and include the following code:

import React from "react";

class App extends React.Component {

    constructor() {
        super();
        this.state = {
            podcasts: []
        }
    }

    async componentDidMount() { }

    render() {
        return (
            <div></div>
        );
    }

}

export default App;

The goal will be to query an API with podcast information. The querying will happen in the componentDidMount method and the result will be rendered in the render function.

For this particular tutorial, we’re not going to be using hooks.

Interacting with GraphQL using Axios and React

We know that most implementations of GraphQL use standard HTTP. There are many options for making HTTP requests in JavaScript, but one of the more popular is to use a library like axios.

From the command line, execute the following command:

npm install axios --save

Now that we have the package installed, we can start to use it in our project. Open the project’s src/App.js file and include the following:

import React from "react";
import axios from "axios";

class App extends React.Component {

    constructor() {
        super();
        this.state = {
            podcasts: []
        }
    }

    makeGraphQLQuery(query) {
        return axios({
            "method": "POST",
            "url": "https://<GRAPHQL_URL_HERE>",
            "data": {
                "query": query
            }
        }).then(response => response.data);
    }

    async componentDidMount() {
        try {
            let result = await this.makeGraphQLQuery(`
                {
                    podcasts {
                        name,
                        author
                    }
                }    
            `);
            this.setState({ podcasts: result.data.podcasts });
        } catch (exception) {
            console.error(exception);
        }
    }

    render() {
        return (
            <div>
                {
                    this.state.podcasts.map((podcast, key) => {
                        return <p key={key}>{podcast.name} by {podcast.author}</p>
                    })
                }
            </div>
        );
    }

}

export default App;

We have quite a few things happening in the above code. First you’ll notice that we’ve imported the axios library. Next you’ll notice the makeGraphQLQuery function:

makeGraphQLQuery(query) {
    return axios({
        "method": "POST",
        "url": "https://<GRAPHQL_URL_HERE>",
        "data": {
            "query": query
        }
    }).then(response => response.data);
}

We’ve created this function to reduce some of the code that we have to create long term. In this example we’re using axios to execute a POST request against a GraphQL URL. The payload of the request includes a query that we define in the componentDidMount method.

In the componentDidMount method we have the following:

async componentDidMount() {
    try {
        let result = await this.makeGraphQLQuery(`
            {
                podcasts {
                    name,
                    author
                }
            }    
        `);
        this.setState({ podcasts: result.data.podcasts });
    } catch (exception) {
        console.error(exception);
    }
}

Assuming we have a GraphQL API query called podcasts with a schema that includes a name and author field, the above code will execute the request and store the results in the application state.

This brings us to rendering the results of the query.

render() {
    return (
        <div>
            {
                this.state.podcasts.map((podcast, key) => {
                    return <p key={key}>{podcast.name} by {podcast.author}</p>
                })
            }
        </div>
    );
}

We iterate each of the results of our query and create an HTML tag for each.

The same kind of simple HTTP request can be made with a JavaScript fetch command, but my preference is in axios.

Leveraging Apollo to Query a GraphQL API in React

A lot of the GraphQL community prefers to use one of the available packages that Apollo offers. Whether you’re using Angular, Vue.js, or React, Apollo has a solution available.

Let’s rollback our application to before we included any kind of axios code. It should look something like this:

import React from "react";

class App extends React.Component {

    constructor() {
        super();
        this.state = {
            podcasts: []
        }
    }

    async componentDidMount() { }

    render() {
        return (
            <div></div>
        );
    }

}

export default App;

Now we need to install the various GraphQL packages that Apollo offers. From the command line, execute the following command:

npm install apollo-boost @apollo/react-hooks graphql

A lot of what you see here can be found in the official documentation for React. I’ve just put my own spin on it to try to make it a little easier to follow.

With the libraries installed, open the project’s src/App.js file and make it look like the following:

import React from "react";
import ApolloClient from "apollo-boost";
import gql from "graphql-tag";

class App extends React.Component {

    constructor() {
        super();
        this.state = {
            podcasts: []
        }
    }

    async componentDidMount() {
        try {
            const client = new ApolloClient({
                uri: "https://<GRAPHQL_URL_HERE>",
            });
            let podcasts = await client.query({
                query: gql`
                {
                    podcasts {
                        name,
                        author
                    }
                }
            `
            }).then(result => result.data.podcasts);
            this.setState({ podcasts: podcasts });
        } catch (exception) {
            console.error(exception);
        }
    }

    render() {
        return (
            <div>
                {
                    this.state.podcasts.map((podcast, key) => {
                        return <p key={key}>{podcast.name} by {podcast.author}</p>
                    })
                }
            </div>
        );
    }

}

export default App;

In the above code we’re using the same theoretical GraphQL API, but with Apollo instead of axios. This means that the only code that changed was in the componentDidMount method. However, we did import the libraries for Apollo that were previously downloaded.

Take a look at the componentDidMount method:

async componentDidMount() {
    try {
        const client = new ApolloClient({
            uri: "https://<GRAPHQL_URL_HERE>",
        });
        let podcasts = await client.query({
            query: gql`
            {
                podcasts {
                    name,
                    author
                }
            }
        `
        }).then(result => result.data.podcasts);
        this.setState({ podcasts: podcasts });
    } catch (exception) {
        console.error(exception);
    }
}

In this example, we are creating an ApolloClient that points at a particular GraphQL API. Next we create a query and store the results in the podcasts state variable.

By the end of this, the render function updates and the podcasts are rendered on the screen.

Conclusion

You just saw two options when it comes to interacting with a GraphQL API using React. While these examples only demonstrated read-only queries, the same code can be applied towards mutations as well.

My personal preference is to use axios rather than Apollo because I feel like I have more flexibility, but there isn’t a wrong choice.

If you want to see more options when it comes to making HTTP requests, check out my previous tutorial titled, Execute HTTP Requests in JavaScript Applications.

Like I mentioned previously, this particular tutorial did not use hooks, so things would change a bit if that is the route you wanted to take.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.