rtk-query connecting-the-api-slice-to-the-store

Maliethy·2022년 2월 25일
0

react error

목록 보기
7/7

1. issue

next build 후 dispatch(rtkApi.util.invalidateTags(['NoneExportLists'])); 와 같이 rtkApi.util.invalidateTags method가 작동하지 않는 문제가 발생했다.

const handleClickCheckNoneExportButton = useCallback(() => {
    if (detailSearchType && !detailSearchValue.trim()) {
      message.warn('상세조건을 입력해주세요');
      return;
    }

    setStartIndex(0);
  dispatch(rtkApi.util.invalidateTags(['NoneExportLists']));// 이 부분
  
    if (!!omsID) {
      setSkipGetNoneExportListsQuery(false);
    } else {
      setSkipGetAdminNoneExportListsQuery(false);
    }
  }, [startDate, endDate, startIndex, detailSearchType, detailSearchValue, center, omsID]);

2. solution

공식문서의 API slice를 store와 연결하는 설정부분을 확인해보았더니 middleware를 설정해주지 않아 발생한 문제였다. 원래 store 설정을 다음과 같이 했다.
/redux/store/configureStore.ts

 store = configureStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) =>
           isDev
        ? getDefaultMiddleware().concat(logger).concat(rtkApi.middleware)
        : getDefaultMiddleware(),//이 부분
    devTools: isDev,
  });

  return store;
};

공식문서의 store 설정 관련 부분에 대한 설명과 예시는 다음과 같다.

Connecting the API slice to the store​
Now that we have our API definition created, we need to hook it up to our store. In order to do that, we will need to use the reducerPath and middleware properties from our created api. This will allow the store to process the internal actions that the generated hook uses, allows the generated API logic to find the state correctly, and adds the logic for managing caching, invalidation, subscriptions, polling, and more.

src/store.ts

import { configureStore } from '@reduxjs/toolkit'
import { pokemonSlice } from './services/pokemonSlice'
import { api } from './services/api'

export const store = configureStore({
  reducer: {
    pokemon: pokemonSlice.reducer,
    [api.reducerPath]: api.reducer,
  },
  middleware: (gDM) => gDM().concat(api.middleware),
})

export type RootState = ReturnType<typeof store.getState>

reduxjs/toolkit의 configureStore를 설정할 때 getDefaultMiddleware().concat(rtkApi.middleware) 와 같이 middleware 설정을 해주어야 api slice가 작동한다. rtkApi.middleware가 caching, invalidation, subscriptions, polling 등등을 관리해주기 때문이다.

/redux/store/configureStore.ts

import { configureStore } from '@reduxjs/toolkit';
import { createWrapper } from 'next-redux-wrapper';
import logger from 'redux-logger';
import { combineReducers } from 'redux';
import { HYDRATE } from 'next-redux-wrapper';
import { userSlice } from '../reducers/user';
import { orderSlice } from '../reducers/order';
import { storeSlice } from '../reducers/store';
import { centerSlice } from '@redux/reducers/center';
import { rtkApi } from '../services';
import { useDispatch, TypedUseSelectorHook, useSelector } from 'react-redux';

export let store;
const isDev = process.env.NODE_ENV === 'development';

const rootReducer = (state, action) => {
  switch (action.type) {
    case HYDRATE:
      return action.payload;
    default: {
      const combinedReducer = combineReducers({
        user: userSlice.reducer,
        order: orderSlice.reducer,
        store: storeSlice.reducer,
        center: centerSlice.reducer,
        [rtkApi.reducerPath]: rtkApi.reducer,
      });
      return combinedReducer(state, action);
    }
  }
};
const createStore = () => {
  store = configureStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) =>
           isDev
        ? getDefaultMiddleware().concat(logger).concat(rtkApi.middleware)
        : getDefaultMiddleware().concat(rtkApi.middleware),//이 부분
    devTools: isDev,
  });

  return store;
};

const wrapper = createWrapper(createStore, {
  debug: isDev,
});

export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

export default wrapper;

https://redux-toolkit.js.org/rtk-query/usage/migrating-to-rtk-query#connecting-the-api-slice-to-the-store

profile
바꿀 수 있는 것에 주목하자

0개의 댓글