RTK query는 React-query, SWR과 비슷한 라이브러리이다. 이들 기술은 클라이언트와 서버의 관계를 새롭게 정립하며, 서버와 통신하는 방법에 대한 기술을 제공한다.

RTK query는 Redux를 태생으로 하는 기술이나 반드시 함께 쓸 필요가 없이 독립적인 라이브러리이다.

import React from "react";
import { api } from "./app/api";
const Count = ({ name }) => {
	// useGetCountQuery : 데이터를 읽기 전용으로 가져오며 객체를 리턴한다.
  // status, endpointNamestatus, requestIdstatus, originalArgsstatus, startedTimeStampstatus, isUninitializedstatus, isLoadingstatus, isSuccessstatus, isErrorstatus, datastatus, currentDatastatus, isFetchingstatus, refetchstatus
  const query = api.useGetCountQuery({ name });
  const mutation = api.useSetCountMutation(); // useSetCountMutation: 배열을 리턴
  const setCount = mutation[0]; // 배열의 첫 번째 원소인 함수를 수동 실행
  if (query.isLoading) {
    return <>Loading</>;
  }

  return (
    <div>
      <button
        onClick={async () => {
          await setCount({ name, value: query.data + 1 }); // 첫 번째 원소함수는 promise로 응답 값을 전달
        }}
      >
				{/* 두 번째 원소 객체의 isLoading 사용 가능 */}
        {mutation[1].isLoading ? "updating..." : ""}
        {query.isFetching ? "fetching..." : ""}
        {name} {query.data}
      </button>
    </div>
  );
};
export default function App() {
  return (
    <>
      <Count name="egoing" />
    </>
  );
}

위 구조를 만들어주는 api.js 파일은 아래와 같다.

./app/api

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: "<https://example.com/api>" }),
  tagTypes: ["Count"], // 데이터 mutation 후 새로운 데이터로 갱신해준다.
  endpoints: (builder) => ({
    getCount: builder.query({
      query: ({ name }) => `count/${name}`,
      providesTags: (result, error, arg) => {
				// subscription tags를 여기에 등록
        console.log(result, error, arg);
        return [{ type: "Count", id: arg.name }];
      }
    }),
    setCount: builder.mutation({
      query: ({ name, value }) => {
        return {
          url: `count/${name}`,
          method: "POST",
          body: { value }
        };
      },
			// subscription tags를 여기에 등록
      invalidatesTags: (result, error, arg) => [{ type: "Count", id: arg.name }]
    })
  })
});

/*
api = {
	injectEndpoints: ƒ injectEndpoints() {}
	enhanceEndpoints: ƒ enhanceEndpoints() {}
	reducerPath: "api"
	endpoints: Object
	internalActions: Object
	util: Object
	reducer: ƒ reducer() {}
	middleware: ƒ middleware() {}
	usePrefetch: ƒ usePrefetch() {}
	useGetCountQuery: ƒ useQuery() {}
	useLazyGetCountQuery: ƒ useLazyQuery() {}
	useSetCountMutation: ƒ () {}
}
*/