learn react ui logoLearnReactUI
Query with Fetch API, Axios and GraphQL

Query with FetchAPI, Axios and GraphQL

In this example, we'll examine how we can perform Fetch operations through different libraries or Web APIs.

Links:

Demos:

Network Operations

Network Knowledge

A. Fetch API

A built-in API available in every browser. You can make HTTP requests using this API as shown below:

const handleFetch = (apiURL) => {
  fetch(apiURL)
    .then((response) => response.json())
    .then((data) => console.log("data fetched", data))
    .catch(function (error) {
      console.log("request failed", error);
    });
};

B. Axios API

A library developed to handle complexities in HTTP requests before Fetch API came along, with some extra features. For example, you can read about Interceptors in this blog post.

Notice how the only thing that changes in the code below is essentially fetch → axios:

const handleFetch = (apiURL) => {
  axios
    .get(apiURL)
    .then(function (response) {
      console.log("data fetched", response?.data);
    })
    .catch(function (error) {
      console.log("request failed", error);
    })
    .finally(function () {});
};

C. GraphQL

GraphQL was developed specifically for situations where you need to provide data through different channels like Mobile, Desktop, Web, etc., similar to RestAPI, but where you want this data to change dynamically according to requests. Unlike REST, you define a Req/Resp schema, and the data will be populated and retrieved from the server according to this schema.

Here's an example using the graphql-request library (you could also use Apollo GraphQL Client):

import { gql, request } from "graphql-request";

const queryCities = gql`
  query GetAllCities {
    cities {
      label
      value
    }
  }
`;

const handleFetch = (query) => {
  (async () => {
    try {
      const data = await request(graphqlApiUri, query);
      console.log(data);
    } catch (error) {
      console.error("Error occurred while fetching data:", error);
    }
  })();
};

Mock Service Worker with Virtual Server

First, let's define our static data:

export const cities = [
  { label: "Istanbul", value: "IST" },
  { label: "Ankara", value: "ANK" },
];

Rest Handler

Let's write a handler that can handle REST requests from the client:

export const cityHandlers = [
  http.get(`${restApiUri}/address/cities`, async () => {
    return HttpResponse.json(cities);
  }),

  http.get(`${restApiUri}/address/districts`, async () => {
    return HttpResponse.json(districts);
  }),

  http.get(`${restApiUri}/address/neighborhoods`, async () => {
    return HttpResponse.json(neighborhoods);
  }),
];

GraphQL Handler

Let's write a GraphQL handler that can handle requests from the client:

const myGraphQL = graphql.link(graphqlApiUri);

export const qqlCityHandlers = [
  myGraphQL.query("GetAllCities", () => {
    return HttpResponse.json({
      data: cities,
    });
  }),

  myGraphQL.query("GetAllDistricts", () => {
    return HttpResponse.json({
      data: districts,
    });
  }),

  myGraphQL.query("GetAllNeighborhoods", () => {
    return HttpResponse.json({
      data: neighborhoods,
    });
  }),
];

Since GraphQL has a more dynamic structure, it takes query, mutation variable/response schema structures. Tools like Apollo GraphQL help create these schemas on the server, but in our examples, we'll handle these operations ourselves.