본문으로 건너뛰기

GraphQL에서 재사용 가능한 React 컴포넌트로 변환 — Numio

Document 패널의 각 operation에 대해 타입이 지정된 데이터 조회 코드를 생성합니다. React Apollo hooks(기본값), Apollo Angular 서비스, Stencil Apollo 컴포넌트, urql hooks 중 하나를 TypeScript 스키마 타입 및 operation 타입과 함께 출력합니다.

방금 작성한 쿼리로 Apollo Client React 앱에서 바로 쓸 useXQuery와 useXLazyQuery hooks를 얻습니다.

GraphQL Schema

Document

이럴 때 사용하세요

  • 방금 작성한 쿼리로 Apollo Client React 앱에서 바로 쓸 useXQuery와 useXLazyQuery hooks를 얻습니다.
  • 클라이언트를 고르기 전에 같은 operation이 Apollo Angular injectable 서비스와 urql hook으로는 어떻게 생기는지 비교합니다.

사용 방법

  1. GraphQL Schema 편집기에 스키마를, Document 편집기에 이름 있는 query, mutation, subscription을 붙여 넣습니다.
  2. 출력 드롭다운에서 대상을 선택합니다: TypeScript React Apollo, TypeScript Apollo Angular, TypeScript Stencil Apollo, TypeScript urql.
  3. 생성된 document 상수(예: GetUserDocument)와 hooks, 서비스 또는 컴포넌트를 프로젝트에 복사합니다.

GraphQL 스키마 + document

# GraphQL Schema editor
type Query {
  user(id: ID!): User
}

type User {
  id: ID!
  name: String
  tags: [String!]!
}

# Document editor
query GetUser($id: ID!) {
  user(id: $id) { id name }
}

TypeScript 컴포넌트와 hooks

import { gql } from "@apollo/client"
import * as Apollo from "@apollo/client"
…
export const GetUserDocument = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
    }
  }
`
…
export function useGetUserQuery(
  baseOptions: Apollo.QueryHookOptions<GetUserQuery, GetUserQueryVariables>,
) {
  const options = { ...defaultOptions, ...baseOptions }
  return Apollo.useQuery<GetUserQuery, GetUserQueryVariables>(
    GetUserDocument,
    options,
  )
}
…

세부 정보 및 제한 사항

모든 옵션은 먼저 @graphql-codegen/typescript와 typescript-operations를 실행하므로, 출력에는 전체 스키마 타입과 operation 타입도 포함됩니다(위 예시에서는 생략).

React Apollo는 gql과 hooks를 @apollo/client에서 가져오고, urql과 Stencil은 gql을 graphql-tag에서 가져옵니다. Apollo Angular는 GetUserGQL 같은 @Injectable 클래스를 생성합니다.

Document 편집기에 유효한 operation이 없으면 hooks나 컴포넌트가 생성되지 않습니다. 스키마와 맞지 않는 document는 경고 주석과 함께 건너뜁니다. 생성은 브라우저 Web Worker에서 실행됩니다.

FAQ

useGetUserQuery에서 baseOptions가 필수인 이유는 무엇인가요?

이 쿼리에는 non-null 변수($id: ID!)가 있으므로 생성된 hook은 variables가 담긴 옵션을 필수로 요구합니다. 필수 변수가 없는 쿼리에서는 baseOptions 매개변수가 선택 사항입니다.

React Apollo 출력에 lazy query hooks도 포함되나요?

네. 쿼리마다 useXQuery와 useXLazyQuery, 그리고 GetUserQueryHookResult, GetUserQueryResult 같은 결과 타입 별칭을 생성합니다. mutation에는 useXMutation hook이 생성됩니다.

withHooks나 import 경로 같은 플러그인 옵션을 바꿀 수 있나요?

아니요. 페이지는 각 플러그인을 기본 설정으로 실행하며, 출력 대상 드롭다운만 제공합니다.

사양 및 참고 자료