리액트에서 RTK Query는 쿼리와 엔드포인트들을 위해 각각의 query와 mutation endpoints에서 자동으로 생성되는 리액트 hooks인 createApi를 exports하는것에서부터 시작됩니다.
타입스크립트 사용자를 위한 자동생성 리액트 hooks를 사용할려면 TS4.1+ 버전을 사용해야 합니다.
// Need to use the React-specific entry point to allow generating React hooksimport { createApi, fetchBaseQuery } from'@reduxjs/toolkit/query/react'importtype { Pokemon } from'./types'// Define a service using a base URL and expected endpointsexportconstpokemonApi=createApi({ reducerPath:'pokemonApi', baseQuery:fetchBaseQuery({ baseUrl:'https://pokeapi.co/api/v2/' }),endpoints: (builder) => ({ getPokemonByName:builder.query<Pokemon,string>({query: (name) =>`pokemon/${name}`, }), }),})// Export hooks for usage in function components, which are// auto-generated based on the defined endpointsexportconst { useGetPokemonByNameQuery } = pokemonApi
// Need to use the React-specific entry point to allow generating React hooksimport { createApi, fetchBaseQuery } from'@reduxjs/toolkit/query/react'// Define a service using a base URL and expected endpointsexportconstpokemonApi=createApi({ reducerPath:'pokemonApi', baseQuery:fetchBaseQuery({ baseUrl:'https://pokeapi.co/api/v2/' }),endpoints: (builder) => ({ getPokemonByName:builder.query({query: (name) =>`pokemon/${name}`, }), }),})// Export hooks for usage in function components, which are// auto-generated based on the defined endpointsexportconst { useGetPokemonByNameQuery } = pokemonApi
예전 TS 버전을 위해서 api.endpoints.[endpointName].useQuery/useMutation로 같을 hooks을 사용할 수 있습니다.
Args - 함수의 첫번째 파라미터 타입입니다. endpoint의 query 프로퍼티에서 반환받은 결과가 여기에 전달됩니다.
Result - success 케이스일때 반환될 data 프로퍼티 타입입니다. 모든 query와 mutation들이 같은 타입을 반환하지 않는한 이 타입을 unknown으로 하고 밑에서처럼 각각의 타입을 지정하는걸 추천합니다.
Error - error 케이스일때 반환될 error 프로퍼티 타입입니다. 이 타입은 API 정의의 endpoints에서 사용되는 모든 queryFn에도 적용됩니다.
DefinitionExtraOptions - 함수의 세번째 파라미터 타입입니다. endpoint의 extraOption 프로퍼티 값이 여기에 전달됩니다.
Meta - baseQuery를 호출할때 반환될 수 있는 meta 프로퍼티의 타입입니다. meta 프로퍼티는 transformResponse의 두번째 인자로 접근 가능합니다.
노트
baseQuery에서 반환받은 meta 프로퍼티는 에러가 thorw된 경우에는 반환이 되지 않아서 잠재적으로 undefined일 수 있습니다. meta 프로퍼티에 접근할때는 optional chaining같은 방법으로 접근해야합니다.
간단한 타입스크립트 baseQuery 예시
import { createApi, BaseQueryFn } from'@reduxjs/toolkit/query'constsimpleBaseQuery:BaseQueryFn<string,// Argsunknown,// Result { reason:string },// Error { shout?:boolean },// DefinitionExtraOptions { timestamp:number } // Meta> = (arg, api, extraOptions) => {// `arg` has the type `string`// `api` has the type `BaseQueryApi` (not configurable)// `extraOptions` has the type `{ shout?: boolean }constmeta= { timestamp:Date.now() }if (arg ==='forceFail') {return { error: { reason:'Intentionally requested to fail!', meta, }, } }if (extraOptions.shout) {return { data:'CONGRATULATIONS', meta } }return { data:'congratulations', meta }}constapi=createApi({ baseQuery: simpleBaseQuery,endpoints: (builder) => ({ getSupport:builder.query({query: () =>'support me', extraOptions: { shout:true, }, }), }),})
간단한 타입스크립트 baseQuery 예시
import { createApi } from'@reduxjs/toolkit/query'constsimpleBaseQuery= (arg, api, extraOptions) => {// `arg` has the type `string`// `api` has the type `BaseQueryApi` (not configurable)// `extraOptions` has the type `{ shout?: boolean }constmeta= { timestamp:Date.now() }if (arg ==='forceFail') {return { error: { reason:'Intentionally requested to fail!', meta, }, } }if (extraOptions.shout) {return { data:'CONGRATULATIONS', meta } }return { data:'congratulations', meta }}constapi=createApi({ baseQuery: simpleBaseQuery,endpoints: (builder) => ({ getSupport:builder.query({query: () =>'support me', extraOptions: { shout:true, }, }), }),})
query와 mutation endpoints 작성하기
endpoints는 builder syntax를 이용해서 정의된 오브젝트입니다. query와 mutation endpoints는 제너릭 포맷인 <ResultType, QueryArg>으로 타입을 제공할 수 있습니다.
ResultType - 쿼리에서 반환되는 최종 데이터 타입, optional한 transformResponse를 factoring합니다.
만약 transformResponse가 없다면, success query가 이 타입을 대신 반환합니다.
만약 transformResponse가 있다면, 초기 쿼리가 반환하는 타입때문에 transformResponse의 input 타입이 있어야 합니다. transformResponse의 반환 타입을 ResultType과 같아야 합니다.
만약 QueryFn이 query대신 쓰인다면, success case일때 다음과 같은 형태의 값을 반환해야 합니다:
{ data: ResultType}
QueryArg - endpoint의 query 프로퍼티이거나 queryFn을 대신 사용하면 queryFn의 첫번째 파라미터의 타입입니다?.( The type of the input that will be passed as the only parameter to the query property of the endpoint, or the first parameter of a queryFn property if used instead.)
타입스크립트로 endpoints 정의하기
import { createApi, fetchBaseQuery } from'@reduxjs/toolkit/query/react'interfacePost { id:number name:string}constapi=createApi({ baseQuery:fetchBaseQuery({ baseUrl:'/' }),endpoints: (build) => ({// ResultType QueryArg// v v getPost:build.query<Post,number>({// inferred as `number` from the `QueryArg` type// vquery: (id) =>`post/${id}`,// An explicit type must be provided to the raw result that the query returns// when using `transformResponse`// vtransformResponse: (rawResult: { result: { post:Post } }, meta) => {// ^// The optional `meta` property is available based on the type for the `baseQuery` used// The return value for `transformResponse` must match `ResultType`returnrawResult.result.post }, }), }),})
endpoints 정의하기
import { createApi, fetchBaseQuery } from'@reduxjs/toolkit/query/react'constapi=createApi({ baseQuery:fetchBaseQuery({ baseUrl:'/' }),endpoints: (build) => ({// ResultType QueryArg// v v getPost:build.query({// inferred as `number` from the `QueryArg` type// vquery: (id) =>`post/${id}`,// An explicit type must be provided to the raw result that the query returns// when using `transformResponse`// vtransformResponse: (rawResult, meta) => {// ^// The optional `meta` property is available based on the type for the `baseQuery` used// The return value for `transformResponse` must match `ResultType`returnrawResult.result.post }, }), }),})
노트
queries와 mutations은 위의 방식대신 baseQuery를 통해 반환 타입을 정의할 수 있습니다. 그러나 모든 query와 mutation들이 같은 타입을 반환하지 않는 한 baseQuery의 반환 타입을 unkown으로 두는 것을 추천합니다.
import { createApi, fetchBaseQuery } from'@reduxjs/toolkit/query/react'import { getRandomName } from'./randomData'interfacePost { id:number name:string}constapi=createApi({ baseQuery:fetchBaseQuery({ baseUrl:'/' }),endpoints: (build) => ({// ResultType QueryArg// v v getPost:build.query<Post,number>({// inferred as `number` from the `QueryArg` type// vqueryFn: (arg, queryApi, extraOptions, baseQuery) => {constpost:Post= { id: arg, name:getRandomName(), }// For the success case, the return type for the `data` property// must match `ResultType`// vreturn { data: post } }, }), }),})
import { createApi, fetchBaseQuery } from'@reduxjs/toolkit/query/react'import { getRandomName } from'./randomData'constapi=createApi({ baseQuery:fetchBaseQuery({ baseUrl:'/' }),endpoints: (build) => ({// ResultType QueryArg// v v getPost:build.query({// inferred as `number` from the `QueryArg` type// vqueryFn: (arg, queryApi, extraOptions, baseQuery) => {constpost= { id: arg, name:getRandomName(), }// For the success case, the return type for the `data` property// must match `ResultType`// vreturn { data: post } }, }), }),})
queryFn이 항상 반환해야하는 error 타입은 createApi가 제공하는 baseQuery에 의해서 결정됩니다.
This is often written by spreading the result of mapping the received data into an array, as well as an additional item in the array for the 'LIST' ID tag. When spreading the mapped array, by default, TypeScript will broaden the type property to string. As the tag type must correspond to one of the string literals provided to the tagTypes property of the api, the broad string type will not satisfy TypeScript. In order to alleviate this, the tag type can be cast as const to prevent the type being broadened to string.
RTK Query provides the ability to conditionally skip queries from automatically running using the skip parameter as part of query hook options (see Conditional Fetching).
TypeScript users may find that they encounter invalid type scenarios when a query argument is typed to not be undefined, and they attempt to skip the query when an argument would not be valid.
API definition
import { createApi, fetchBaseQuery } from'@reduxjs/toolkit/query/react'import { Post } from'./types'exportconstapi=createApi({ baseQuery:fetchBaseQuery({ baseUrl:'/' }),endpoints: (build) => ({// Query argument is required to be `number`, and can't be `undefined`// V getPost:build.query<Post,number>({query: (id) =>`post/${id}`, }), }),})exportconst { useGetPostQuery } = api
API definition
import { createApi, fetchBaseQuery } from'@reduxjs/toolkit/query/react'exportconstapi=createApi({ baseQuery:fetchBaseQuery({ baseUrl:'/' }),endpoints: (build) => ({// Query argument is required to be `number`, and can't be `undefined`// V getPost:build.query({query: (id) =>`post/${id}`, }), }),})exportconst { useGetPostQuery } = api
Using skip in a component
import { useGetPostQuery } from'./api'functionMaybePost({ id }: { id?:number }) {// This will produce a typescript error:// Argument of type 'number | undefined' is not assignable to parameter of type 'number | unique symbol'.// Type 'undefined' is not assignable to type 'number | unique symbol'.// @ts-expect-error id passed must be a number, but we don't call it when it isn't a numberconst { data } =useGetPostQuery(id, { skip:!id })return <div>...</div>}
Using skip in a component
import { useGetPostQuery } from'./api'functionMaybePost({ id }: { id?:number }) {// This will produce a typescript error:// Argument of type 'number | undefined' is not assignable to parameter of type 'number | unique symbol'.// Type 'undefined' is not assignable to type 'number | unique symbol'.// @ts-expect-error id passed must be a number, but we don't call it when it isn't a numberconst { data } =useGetPostQuery(id, { skip:!id })return <div>...</div>}
While you might be able to convince yourself that the query won't be called unless the id arg is a number at the time, TypeScript won't be convinced so easily.
RTK Query provides a skipToken export which can be used as an alternative to the skip option in order to skip queries, while remaining type-safe. When skipToken is passed as the query argument to useQuery, useQueryState or useQuerySubscription, it provides the same effect as setting skip: true in the query options, while also being a valid argument in scenarios where the arg might be undefined otherwise.
Using skipToken in a component
import { skipToken } from'@reduxjs/toolkit/query/react'import { useGetPostQuery } from'./api'functionMaybePost({ id }: { id?:number }) {// When `id` is nullish, we will still skip the query.// TypeScript is also happy that the query will only ever be called with a `number` nowconst { data } =useGetPostQuery(id ?? skipToken)return <div>...</div>}