Nextjs12 버전에서 redux-toolkit 타입스크립트로 설정하는 방법

togongs·2022년 10월 21일
0

2022

목록 보기
1/19
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import { createWrapper } from 'next-redux-wrapper';
import authReducer from './reducers/authReducer';
import productReducer from './reducers/productReducer';

export const createStore = () => {
  const store = configureStore({
    reducer: { auth: authReducer, product: productReducer },
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware({
        serializableCheck: false,
      }),
  });
  return store;
};

export type AppStore = ReturnType<typeof createStore>;
export type RootState = ReturnType<typeof createStore>; // RootState 타입
export type AppDispatch = AppStore['dispatch']; // dispatch 타입
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action
>; // Thunk 를 위한 타입

export const wrapper = createWrapper(createStore);
import { AppDispatch } from '../redux/store';

const dispath = useDispatch<AppDispatch>();
const productSlice = createSlice({
  name: 'product',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getAllProducts.pending, (state, action: AnyAction) => {
      console.log('pending 상태', action); // Promise가 pending일때 dispatch
      state.isLoading = true;
    }),
      builder.addCase(getAllProducts.fulfilled, (state, action: AnyAction) => {
        console.log('fulfilled 상태', action); // Promise가 fullfilled일 때 dispatch
        state.isLoading = false;
        state.productList = action.payload;
      }),
      builder.addCase(getAllProducts.rejected, (state, action: AnyAction) => {
        console.log('rejected 상태', action); // Promise가 rejected일 때 dispatch
        state.isLoading = false;
        state.error = action.payload; // catch 된 error 객체를 state.error에 넣습니다.
      });
  },
});
  • dispatch를 사용하기 위해 store.tstype설정
  • useDispatchactionAppDispatch 지정

참고 - https://curryyou.tistory.com/501

profile
개발기록

0개의 댓글