이전에 만든 next.js 에 undo, redo 기능을 만들어보자.
라이브러리 써서 쉽게 만들어볼 예정.
npm install redux-undo
ㄱㄱ
희망편이기 때문에 참 쉬울 예정이다.
기본 구조등은 이전 포스트에 만들어둔 내용을 참고 하면 좋을 듯...
링크 남겨둔다.
암튼 저렇게 만들어 둔 상태에서 modules/index.js 를 좀 손봐주기로 하자.
import {combineReducers} from "redux";
import {HYDRATE} from "next-redux-wrapper";
import undoable from 'redux-undo';
import test from './test';
const reducer =(state,action)=> {
if (action.type === HYDRATE) {
return {
...state,
...action.payload
};
}
return combineReducers({
test:undoable(test)
})(state,action)
}
export default reducer;
이거 보면 undoable 이라는 함수를 하나 가져오고 이놈이
combineReducers에서 test라는 리듀서를 undoable하게 만들어 줄 것 이라는점을
대충 짐작해 볼 수 있다.
이제 액션도 하나 손봐주자.
const COUNT = 'COUNT'
export const testCount =()=>{
return{
type:COUNT,
}
};
const initialState ={value:'ㄱ'};
const test = (state=initialState,action)=>{
switch (action.type){
case COUNT:
return {...state,value: state.value+"ㄴ"}
default:
return state
}
}
export default test
testCount라는 함수를 dispatch하면 value에 'ㄴ'이 계속 붙게될 예정이다.
작업할 파일로 들어가보자.
import { ActionCreators } from "redux-undo";
import {useDispatch, useSelector} from "react-redux";
import {testCount} from "../../../store/modules/test";
export default function 작업파일() {
const item = useSelector(state => state.test.present.value)
const Add=()=>{
dispatch(testCount());
console.log(item)
}
const Undo=()=>{
dispatch(ActionCreators.undo());
console.log(item)
}
const Redo=()=>{
dispatch(ActionCreators.redo());
console.log(item)
}
return(
<>
<button onClick={()=> {
Add()
}}>Add</button>
<button onClick={()=> {
Undo()
}}>undo</button>
<button onClick={()=> {
Redo()
}}>redo</button>
</>
)
}
add버튼 누르면 ㄴ 이 하나씩 늘어남.
그리고 undo,redo는
ActionCreators라는 함수를 불러다 dispatch 해주면
잘 작동하는 것을 볼 수 있다.
그리고 아까 undoable로 reducer를 감싸줬기때문에
useSelector로 찾아쓸 때 state.리듀서이름.present 로 찾아야함.
이렇게 쉽고 간단하게 undo,redo 기능을 구현 해 보았다.
끝.
참고로 절망편은 라이브러리 안쓰고 기능구현하기 이다.