본문으로 바로가기

redux toolkit with typescript

category State Management/⚛ Redux 2021. 8. 7. 21:30

회사에서 chrome extension 관련 개발을 하면서 redux를 redux toolkit으로 교체하고 typing까지 해주어야 할 일이 생겼다.

결론적으론 기존 redux보다 훨씬 코드량이 줄어서 만족중.

 

코드 전문을 보자면 다음과 같다.

const initialState = {}

const rootReducer = combineReducers({
  firebase: firebaseReducer,
  firestore: firestoreReducer,
  dropdown: dropdownReducer,
  shortcutAction: shortcutActionReducer
})

const store = configureStore({
  reducer: rootReducer,
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware({
      serializableCheck: false
    }),
  preloadedState: initialState,
  devTools: { trace: true }
})

type RootState = ReturnType<typeof store.getState>
type AppDispatch = typeof store.dispatch

export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

export default store

 

일반 dispatch와 useSelector대신 useAppDispatch와 useAppSelector 를 사용하면 된다. 자동으로 rootState의 타입으로 stater가 추론되고 자동완성도 잘 된다.

 

Slice 부분도 크게 손 볼 곳은 없고, action.payload에 PayloadAction 타이핑만 잘 해주면 된다.

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { Inbox } from 'models/folder'
import { IOriginDocument } from 'query/document-query'
import { EntityType } from './shortcutAction.utils'

export interface DocumentOption {
  documentId: string
  isFolderListOpen: boolean
}

interface IInitialState {
  focusedItem: EntityType
  flattenFolderTree: EntityType[]
  documentOptions: DocumentOption[]
}

const initialState: IInitialState = {
  focusedItem: Inbox,
  flattenFolderTree: [],
  documentOptions: []
}

export const shortcutActionSlice = createSlice({
  name: 'shortcutAction',
  initialState,
  reducers: {
    setFocusedItem: (state, action: PayloadAction<EntityType>) => {
      state.focusedItem = action.payload
    },
    updateFoldersLayer: (
      state,
      action: PayloadAction<Array<EntityType | IOriginDocument>>
    ) => {
      state.flattenFolderTree = action.payload
    },
    updateDocumentOptions: (state, action: PayloadAction<DocumentOption[]>) => {
      state.documentOptions = action.payload
    }
  }
})

export const {
  setFocusedItem,
  updateFoldersLayer,
  updateDocumentOptions
} = shortcutActionSlice.actions

export default shortcutActionSlice.reducer

 

 

ref)

https://redux-toolkit.js.org/tutorials/typescript

https://redux-toolkit.js.org/usage/usage-with-typescript

 


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체