Home RTK Query(리덕스 툴킷 쿼리)
Post
Cancel

RTK Query(리덕스 툴킷 쿼리)

RTK Query란

  • 간편하게 데이터를 가져오고 캐싱하는 로직을 직접 하나하나 작성할 필요가 없음.
  • RTK Query는 Redux Toolkit에 포함된 애드온임

사용 방법

  1. API 서비스 정의
// ./src/redux/service/orderSheet.ts
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import OrderSheet from './orderSheet.type';

// base URL과 엔드포인트들을 정의
export const orderSheetApi = createApi({
  reducerPath: 'orderSheetApi',
  baseQuery: fetchBaseQuery({ baseUrl: process.env.API_URL }),
  endpoints: builder => ({
    getOrderSheet: builder.query<OrderSheet, null>({
      query: () => `/data/db.json`,
    }),
  }),
});

export const { useGetOrderSheetQuery } = orderSheetApi;
  1. Store에 서비스 추가
// ./src/redux/store.ts
import { configureStore } from '@reduxjs/toolkit';
import { setupListeners } from '@reduxjs/toolkit/query';
import { orderSheetApi } from './services/orderSheet';
import { modalSlice } from './slices/modal';
import { orderSheetSlice } from './slices/orderSheet';

export const store = configureStore({
  reducer: {
    [orderSheetApi.reducerPath]: orderSheetApi.reducer,
    orderSheet: orderSheetSlice.reducer,
    modal: modalSlice.reducer,
  },
  middleware: getDefaultMiddleware => getDefaultMiddleware().concat(orderSheetApi.middleware),
});

setupListeners(store.dispatch);
// RootState type
export type RootState = ReturnType<typeof store.getState>;
// App Dispatch type
export type AppDispatch = typeof store.dispatch;
  1. 컴포넌트에서 쿼리 사용
import React, { ReactElement, useState } from 'react';
//redux
import { useAppSelector } from 'hooks';
import { useGetOrderSheetQuery } from 'redux/services/orderSheet';
import { useDispatch } from 'react-redux';
import { renewalOpenState } from 'redux/slices/modal';
//style
import { Modal as MUIModal, Button } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import * as M from './Modal.styled';

const Modal = (): ReactElement => {
  //redux
  const { data, error, isLoading } = useGetOrderSheetQuery(null);

  //이하 생략

Reference

This post is licensed under CC BY 4.0 by the author.