GraphQL fetching data in the client

Hi, in this post we are going to learn how to fetch (get the data) and print the data into our client (browser).

If you want to read the last post please click here GraphQL object association

So we need to call the GraphQL server from the FrontEnd, so let’s create request.js file into our client folder:

In the request.js file we are going to declare the method that will fetch the data that we want to show using the GraphQL endpoint and the query structure:

// GraphQL endpoint
const endpointURL = "http://localhost:9000/graphql";

// Function that will call the GraphQL endpoint passing specific query
// to get the data that the query specifies
export async function loadJobs() {
  const response = await fetch(endpointURL, {
    method: "POST",
    headers: { "content-type": "application/json" }, // The type is json
    body: JSON.stringify({
      // Convert a JavaScript object into a string
      query: `{
                jobs {
                  id 
                  title
                  company {
                    id
                    name
                  }
                }
              }
            `,
    }),
  });

  const responseBody = await response.json(); // Converting the response to json format
  return responseBody.data.jobs;
}

Then in our file

// Dependencies
import React, { Component } from "react";

// Components
import { JobList } from "./JobList";

// Finction that fetch jobs from the GraphQL endpoint
import { loadJobs } from "./request";

export class JobBoard extends Component {
  // To initialize the local state
  constructor(props) {
    super(props);
    this.state = { jobs: [] };
  }

  // When component is mounted then execute the loadJobs() method
  async componentDidMount() {
    const jobs = await loadJobs();
    this.setState({ jobs });
  }

  render() {
    // Getting the jobs data from the local state
    const { jobs } = this.state;

    return (
      <div>
        <h1 className="title">Job Board</h1>
        <JobList jobs={jobs} />
      </div>
    );
  }
}

Now if we open our browser we can see the data in our client (browser)

Note: remember to run the server in other terminal.

By Cristina Rojas.