🍊

TanStack Query (FKA React Query)でGraphQLを使う

2023/03/26に公開

TanStack Queryのセット

QueryClientProviderでアプリにライブラリをセットします。

以下はNext.jsの場合の例です。

src/pages/_app.tsx
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { Hydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import React from 'react'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'

function MyApp({ Component, pageProps }: AppProps) {
  const [queryClient] = React.useState(() => new QueryClient())

  return (
    <QueryClientProvider client={queryClient}>
      <Hydrate state={pageProps.dehydratedState}>
        <Component {...pageProps} />
      </Hydrate>
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}

export default MyApp

カスタムフックを作成

graphql-requestを使ってgraphqlのリクエストを実行する関数を作成してそれをセットしてやります。

useQueryを使う場合

import { useQuery } from '@tanstack/react-query'
import { gql, GraphQLClient } from 'graphql-request'
import { JsonplaceholderUser } from '../../pages/api/graphql/types/graphql'

type TResponse = { jsonplaceholderUser: JsonplaceholderUser } | undefined
type TParams = { id?: string } | undefined

const graphQLClient = new GraphQLClient(`/api/graphql`)

const gqlQuery = gql`
  query Query($id: ID!) {
    jsonplaceholderUser(id: $id) {
      id
      name
      email
    }
  }
`

export const useGetUserApi = ({ id }: TParams = {}) => {
  return useQuery<TResponse>({
    queryKey: ['graphql', 'get', 'user', id],
    queryFn: () => graphQLClient.request(gqlQuery, { id }),
  })
}

useMutationを使う場合

import { Prisma } from '@prisma/client'
import { useMutation } from '@tanstack/react-query'
import { gql, GraphQLClient } from 'graphql-request'

const graphQLClient = new GraphQLClient(`/api/graphql`)

const gqlQuery = gql`
  mutation Mutation($user: createPrismaUserInput!) {
    prismaUser(user: $user) {
      name
      email
    }
  }
`

export const useMutationUserApi = () => {
  const mutationKey = ['graphql', 'create', 'user']
  return useMutation<Prisma.UserCreateInput, unknown, Prisma.UserCreateInput, unknown>({
    mutationKey,
    mutationFn: (params) => graphQLClient.request(gqlQuery, { user: params }),
  })
}

あとはmutateを任意の箇所で実行します。

const { mutate } = useMutationUserApi()
mutate(params)

参考

https://www.takeshape.io/articles/how-to-use-react-query-with-react-and-graphql/

https://tanstack.com/query/v5/docs/react/graphql

サンプル: https://github.com/t-shiratori/react-query-rest-graphql-prisma

Discussion