리덕스 적용하기
먼저 리덕스 폴더 생성후 index.ts 파일을 생성해 주고 안에 아래처럼 적어준다.
import { combineReducers } from "redux";
import word from "./word/reducer";
import { Word } from "./word/types";
export type RootState={
word:Word
}
const rootReducer = combineReducers({
word
});
export default rootReducer
그다음 word 폴더를 만들고 먼저 actions.tsx 를 만들어준다.
import { createAction } from "typesafe-actions";
import { IWords } from "./types";
export const ADD = "word/ADD";
export const UPDATE = "word/UPDATE";
export const DEL = "word/DEL";
export const addWord = createAction(ADD)<{
word: IWords,
}>();
export const updateWord = createAction(UPDATE)<{
word: IWords,
}>();
export const deleteWord = createAction(DEL)<number>();
그다음 types.tsx 를 만들어준다.
import { ActionType } from "typesafe-actions";
import * as actions from "./actions"
export type WordAction = ActionType<typeof actions>;
export interface IWords{
id: number,
word: string,
description: string,
example: string,
}
export type Word = {
word: Array<IWords>,
}
마지막으로 핵심인 리듀서 파일을 reducer.tsx. 로 만들어준다.
import { createReducer } from "typesafe-actions";
import { ADD, DEL, UPDATE } from "./actions";
import { Word, WordAction } from "./types";
import produce from 'immer';
const initailState: Word = {
word: []
}
const word = createReducer<Word, WordAction>(initailState, {
[ADD]: (state, action) => {
return produce(state, draft => {
draft.word.push(action.payload.word)
})
},
[UPDATE]: (state, action) => {
return produce(state, draft => {
if (action.payload.word.id !== undefined && action.payload.word.id !== null) {
draft.word.map((v) => {
if (action.payload.word.id === v.id) {
return draft.word[v.id] = { ...action.payload.word }
} else {
return v
}
})
}
});
},
[DEL]: (state, action) => {
return produce(state, draft => {
draft.word = draft.word.filter(v => {
return v.id !== action.payload
})
});
},
});
export default word
해당 리덕스 의 사용 법은
const updateWord = useCallback(
(word: IWords) => dispatch(addWord({ word: word })),
[dispatch]
);
updateWrod(word);
위와 같은 형식으로 선언해주고 사용하면 된다.