npm i @reduxjs/toolkit
: RTK 코드가 들어있는 본체 (TS 포함되어있음)
npm i react-redux
: React에서 RTK를 연결해주는 코드
components
, pages
, styles
등.. 모두 conventional하게 쓰이는 폴더이다. 이에 추가로 slice를 관리하는 폴더를 store
로 명명하고 사용한다.import {configureStore} from "@reduxjs/toolkit";
import rootReducer from './rootReducer';
const store = configureStore({
reducer: rootReducer,
})
export default store;
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
typeof 메서드로 store의 각 속성에 접근하여 해당하는 type을 선언해준다.
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "./store";
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
export const useAppDispatch= () => useDispatch<AppDispatch>()
import { combineReducers } from "@reduxjs/toolkit";
import addMenuSlice from "@/store/slices/addMenu-slice"
import userSlice from "@/store/slices/user-slice";
import loginSlice from "@/store/slices/loginSlice";
import signUpSlice from "@/store/slices/signUpSlice";
import modeSlice from "@/store/slices/modeSlice";
import postItDataSlice from "./slices/postItDataSlice";
const rootReducer = combineReducers({
addMenu: addMenuSlice,
user: userSlice,
login: loginSlice,
signUp: signUpSlice,
mode: modeSlice,
data: postItDataSlice
});
export default rootReducer;
export interace datatype {
필드 : 데이터 값(참조type~원시type)
}
const initialState : datatype = {
필드 : 데이터 값(datatype에 맞춰야함)
}
const 어쩌고Slice = createSlice {
name:"",
initialState,
reducers:{
메서드들...
}
}
export const 어쩌고Actions = 어쩌고Slice.actions;
export default 어쩌고Slice.reducer;
const dispatch = useAppDispatch();
const userId = useAppSelector((state: RootState) => state.user.userData.userId);
const addFont = (event:React.FormEvent<HTMLFormElement>) => {
...
dispatch(postItDataActions.addData({userId: userId, colName: colName, font: data}));
return
}