TechAE Blogs - Explore now for new leading-edge technologies

TechAE Blogs - a global platform designed to promote the latest technologies like artificial intelligence, big data analytics, and blockchain.

Full width home advertisement

Post Page Advertisement [Top]

Rendering GraphQL object based API on frontend

Rendering GraphQL object based API on Frontend

GraphQL


GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. They are organized in terms of types and fields, not endpoints. Access the full capabilities of your data from a single endpoint.

In this tutorial, we’ll focus on data fetching in React. We’ll demonstrate how to fetch data in React using object-based GraphQL API, complete with code examples, and introduce a handful of approaches to help you determine the best data fetching method for your React project.

GraphQL Benefits:

  • Can be used in any tech stack
  • No over-fetching or under-fetching data
  • Tailored requests
  • Strongly typed
  • Suitable for smaller networks
  • API growth without versioning


React project setup


1. Make a folder and move into that folder by using the following command


code .


2. Create react app 


npx create-react-app myapp


3. Move into the app directory


cd my-app


4. Start the server


npm start


5. In the src folder, make another folder named Component and create the file Api.js in it




6. Create a simple grid in Api.js using bootstrap

import React from "react";

export default function Api() {
    return (
        <div className="py-4" id="text_api">
          <div className="container">
            <div className="row">
              <div className="col-sm-4 text-center">
                <h4>
                  Column 1
                </h4>
                <p>Text</p>
              </div>
              <div className="col-sm-4 text-center">
                <h4>
                Column 2
                </h4>
                <p>Text</p>
              </div>
              <div className="col-sm-4 text-center">
                <h4>Column 3</h4>
                <p>Text</p>
              </div>
            </div>
          </div>
        </div>
      );
    }


7. Call Api.js in the App.js file

import './App.css';

import Api from './Components/Api';

const App = () => {
  return (
      <Api />
  );
};

export default App;


8. Adding Bootstrap CDN in public/index.html

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

Here, is the output


9. Importing a useEffect library

import React, { useEffect } from "react";


10. Make a function for API calling in Api.js using useEffect. In this, we are using the JSON.stringify method to convert Javascript objects into strings. 

function useLaunches() {
    const [launches, setLaunches] = React.useState([]);
    React.useEffect(() => {
        fetch(
            "Your_API_Link",
            {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ query: DATA_QUERY }),
} ) .then((response) => response.json()) .then((data) => setLaunches(data.data.dataFactory));
}, []); return launches; }


11. Use the Javascript function JSON.stringify() to convert it into a string

const DATA_QUERY = `
{
  dataFactory(
    id: "0123"
  ) {
    totalVolume
    totalLiquidity
  }
}
`;


12. Call a function in API function

const launches = useLaunches();

13. Rendering API data on the frontend

export default function Api() {
    const launches = useLaunches();
    return (
        <div className="py-4" id="text_api">
            <div className="container bg-primary">
                <div className="row">
                    <div className="col-sm-6 text-center">
                        <h4>
                            $
                            {launches.totalVolume &&
launches.totalVolume .slice(0, 12)} </h4> <p>Total Volume</p> </div> <div className="col-sm-6 text-center"> <h4> $ {launches.totalLiquidity && launches.totalLiquidity .slice(0, 10)} </h4> <p>Total Liquidity</p> </div> </div> </div> </div> ); }

14. Here is the complete code 

import React, { useEffect } from "react";

const DATA_QUERY = `
{
  dataFactory(
    id: "0123"
  ) {
    totalVolume
    totalLiquidity
  }
}
`;

export default function Api() {
    const launches = useLaunches();
    return (
        <div className="py-4" id="text_api">
            <div className="container bg-primary">
                <div className="row">
                    <div className="col-sm-6 text-center">
                        <h4>
                            $
                            {launches.totalVolume &&
                                launches.totalVolume
                                    .slice(0, 12)}
                        </h4>
                        <p>Total Volume (USD)</p>
                    </div>
                    <div className="col-sm-6 text-center">
                        <h4>
                            $
                            {launches.totalLiquidity &&
                                launches.totalLiquidity
                                    .slice(0, 10)}
                        </h4>
                        <p>Total Liquidity (USD)</p>
                    </div>
                </div>
            </div>
        </div>
    );
}

function useLaunches() {
    const [launches, setLaunches] = React.useState([]);
    React.useEffect(() => {
        fetch(
            "Your_API_Link",
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: DATA_QUERY }), } ) .then((response) => response.json()) .then((data) => setLaunches(data.data.dataFactory)); }, []); return launches; }

Thank you for reading!

Live demo: https://faizaabdullah-code.github.io/my-app/

Github code: FaizaAbdullah-code/my-app (github.com)

So we found a precise method for using an object-based GraphQL API and then rendering on our frontend.

If you found this article helpful, stay tuned for more articles on React.

Cheers!

No comments:

Post a Comment

Thank you for submitting your comment! We appreciate your feedback and will review it as soon as possible. Please note that all comments are moderated and may take some time to appear on the site. We ask that you please keep your comments respectful and refrain from using offensive language or making personal attacks. Thank you for contributing to the conversation!

Bottom Ad [Post Page]