GraphQL with React+TypeScript

Parker cho·2021년 6월 24일
0

최근에 회사에서 영상처리 관련 업무를 하다가 프론트엔드 관련 업무를 하고 싶어서 어쩌다 보니 프론트엔드 개발자가 되었다.

이번 회사에서 진행하는 프로젝트가 프론트엔드에 React, Typescript를 도입하고 PHP로 구성되어있던 백엔드코드를 GrapQL, nodejs 기반 코드로 바꾸는 프로젝트여서 관련된 지식을 공부하고자 GraphQL 예제를 참고하여 간단한 사이트를 구현했다.

기존의 RestApi 와 달리 GraphQL을 사용하면 endpoint가 하나여서 데이터베이스에서 데이터를 가져올 때에 클라이언트 서버 코드를 모두 수정할필요 없이 클라이언트에서만 코드를 수정하여 데이터를 가져 올 수 있는 장점이 있다.

예제 코드가 JS기반으로 작성되어있어서 TypeScript기반 코드로 작성했다.

https://48p1r2roz4.sse.codesandbox.io/
위 링크에 들어가보면 데이터의 타입을 알 수 있다. 타입은 아래와 같이 정의되어있다.

directive @cacheControl(
  maxAge: Int
  scope: CacheControlScope
) on FIELD_DEFINITION | OBJECT | INTERFACE
enum CacheControlScope {
  PUBLIC
  PRIVATE
}

type ExchangeRate {
  currency: String
  rate: String
  name: String
}

type Query {
  rates(currency: String!): [ExchangeRate]
}

scalar Upload

Typescript 에서는 아래와 같이 타입을 정의해주었다.

interface ExchangeRate {
  currency:string | null;
  rate: string | null;
  name: string | null;
}

interface Query {
  rates: Array<ExchangeRate | null> | null;
}

데이터는 Apollo의 useQuery Hook을 사용해 받아왔다

const ExchangeRates: React.FC = () => {
  const { loading, error, data } = useQuery<Query>(EXCHANGE_RATES);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;
  if (data === undefined)return <p>Error :</p>

  return(
  <>
    {
      data.rates.map(({currency, rate}) => {
          return(
            <div>
              <p>
                {currency} : {rate}
              </p>
            </div>
          )
      })
    }
  </>)
}

깃링크: https://github.com/chobe111/GraphQLExample

참고링크: https://www.apollographql.com/docs/react/get-started/

profile
true nobility is being superior to your former self

4개의 댓글

comment-user-thumbnail
2021년 6월 24일

벌새는1초에60번의날개짓을한다.

답글 달기
comment-user-thumbnail
2021년 6월 24일

유익한 정보였어요~

답글 달기
comment-user-thumbnail
2021년 6월 24일

gosu..

답글 달기
comment-user-thumbnail
2021년 6월 25일

잘 보고 갑니다~

답글 달기