Skip to content
Home » Blog » React Series #12: How to consume data from Hygraph and use it in the next.js project

React Series #12: How to consume data from Hygraph and use it in the next.js project

All this time we have been doing internal content. But here is how we can fetch data from Hygraph to show it on the website.

Step 1:

After login to the Hypragh go to your project and in your project go to Project Settings > Content API and enable the defaults.

Step 2:

In your root folder create a file called .env.local

And add this code

NEXT_PUBLIC_MASTER_URL_KEY=xxxx

Replace the xxxx with the key from Hygraph. You can find this in Endpoints

Step 4: Create a Service

Inside app folder create a folder called “_services

Create a file name as GlobalAPI.js

Step 5: Install GrapghQL

npm add graphql-request graphql

Step 6: Here is the base content

const MASTER_URL = 'https://ap-south-1.cdn.hygraph.com/content/' + process.env.NEXT_PUBLIC_MASTER_URL_KEY + '/master'

Step 7: Create a function for your query

const getSlides = async() => {
    const query = gql `
    [Query Goes here]
  `
    const result = await request(MASTER_URL, query)
    return result
}

export default {
    getSlides
}

Here is my query

const getSlides = async() => {
    const query = gql `
        query qSlides {
        slides(first: 1, orderBy: publishedAt_DESC) {
        id
        heading
        image {
          url
        }
        ctaName
        ctaLink
      }
    }
  `
    const result = await request(MASTER_URL, query)
    return result
}

export default {
    getSlides
}

Step 7:

How to use it in the component. here is the import section

"use client";
import { useEffect, useState } from "react";
import GlobalAPI from "../_services/GlobalAPI";

Step 8: Use the react hooks

function Hero() {
  const [slideList, setSlideList] = useState([]); //Declaration

  useEffect(() => {
    getSlideList(); //Usage
  }, []);

  const getSlideList = () => {
    GlobalAPI.getSlides().then((resp) => {
      setSlideList(resp?.slides);
      //console.log(resp);
    });
  };

  return (
    <div className="container">
          {slideList.map((slides, index) => (
              <Image
                src={slides.image.url}
                alt={slides.heading}
                priority={true}
                width={1500}
                height={600}
                style={{
                  maxWidth: "100%",
                  height: "auto",
                }}
              />
          ))}
    </div>
  );
}

This is the fundamental example of how data can be pulled from Hygraph. You can expand this to get complex data.

Leave a Reply

Your email address will not be published. Required fields are marked *