GraphiQL & Gatsby에서 GraphQL 사용 예시

하스레·2022년 4월 15일
0

GraphiQL

GraphQL이 제공하는 IDE. 이를 사용함으로써 어떤 데이터를 요청할 수 있는지 알 수 있음.

GraphiPL IDE 링크: 다음과 같이 gatsby develop으로 서버 실행시 나오는 두 개의 링크 중 아래 거.

GraphiPL IDE

우리 사이트의 메타데이터를 가져오라는 쿼리

Gatsby에서 GraphQL Query

Gatsby에선
1. pages 폴더 내부의 파일
2. Gatsby API를 통해 생성된 페이지의 템플릿 파일
에서만 쿼리 정의가 가능하다.

  • 사용 예시
    metadataQuery 변수에 쿼리를 담아 export 하면 Gatsby 내부적으로 요청을 보내고,
    이에 대한 응답을 파일 안에 InfoPage 컴포넌트 함수에 Props로 전달해준다.
import React, { FunctionComponent } from 'react'
import { graphql } from 'gatsby'
import Text from 'components/Text'

type infoPageProps = {
    "data": {
      "site": {
        "siteMetadata": {
          "author": string,
          "description": string,
          "title": string
        }
      }
    }
  }

const InfoPage: FunctionComponent<infoPageProps> = function ({
    data: {
        site: {
            siteMetadata: { author, description, title },
        },
    },
}) {
    return <div>
        <Text text={title} />
        <Text text={author} />
        <Text text={description} />
    </div>
}

export default InfoPage

export const metadataQuery = graphql `
    {
        site {
            siteMetadata {
                title
                description
                author
            }
        }
    }
`

컴포넌트에서 쿼리 사용 방법: StaticQuery
※ StaticQuery 사용 예시

//StaticQuery
import React from "react"
import { StaticQuery, graphql } from "gatsby"

export default function Header() {
  return (
    <StaticQuery
      query={graphql`
        query HeadingQuery {
          site {
            siteMetadata {
              title
            }
          }
        }
      `}
      render={data => (
        <header>
          <h1>{data.site.siteMetadata.title}</h1>
        </header>
      )}
    />
  )
}
// useStaticQuery
import { useStaticQuery, graphql } from "gatsby"

export const useSiteMetadata = () => {
  const { site } = useStaticQuery(
    graphql`
      query SiteMetaData {
        site {
          siteMetadata {
            title
            siteUrl
            headline
            description
            image
            video
            twitter
            name
            logo
          }
        }
      }
    `
  )
  return site.siteMetadata
}

참고
https://www.gatsbyjs.com/docs/how-to/querying-data/static-query/
https://www.inflearn.com/course/gatsby-%EA%B8%B0%EC%88%A0%EB%B8%94%EB%A1%9C%EA%B7%B8/lecture/76338?tab=note&mm=close

profile
Software Developer

0개의 댓글