redux-thunk와 redux-saga가 있다.enhancer 세팅
//사용방법 1
const enhancer = compose(
applyMiddleware(),
)
//사용방법 2
const enhancer = applyMiddleware();
const store = createStore(reducer, initialState, enhancer);
firstMiddleware (3차 중첩 함수)
store-next, next-action 등 원하는 사이에 원하는 내용을 적을 수 있다.
next를 dispatch로 바꾸어 사용했으나, 원래 공식문서에는 next라고 사용한다.const firstMiddleware = (store) => (dispatch) => (action) => {
//기본 기능이 발생하기 전에 작동하길 원하는 함수 작성
//여기서는 console.log()
console.log(action);
dispatch(action);
//기본 기능이 발생하기 후에 작동하길 원하는 함수 작성
//여기서는 console.log()
console.log(action);
};
const enhancer = applyMiddleware(firstMiddleware );
const store = createStore(reducer, initialState, enhancer);
포인트는 action이 함수이면 비동기라고 암묵적으로 약속하는 것이다.
const thunkMiddleware= (store) => (dispatch) => (action) => {
if(typeof action ==="function") {
//함수로 온 액션을 thunk가 실행해준다.
return action(store.dispatch, store.getState); //리덕스와 프로그래머 사이의 약속
}
return dispatch(action) //기본
};
const enhancer = applyMiddleware(firstMiddleware,thunkMiddleware, );
const store = createStore(reducer, initialState, enhancer);
//비동기
const login = () => {
//위에서 받아온 dispatch와 getState
//thunk가 비동기 액션을 처리해주기 때문에 원하는 비동기 액션을 넣을 수 잇다.
return (dispatch, getState) => {
dispatch(loginRequest(data));
setTimeout(()=>{
dispatch(loginSuccess(
data:{
userId: 1,
nickname:"zerocho"
}
));
}, 2000);
}
}
//동기
const loginRequest = (data)=>{
return {
type: "LOGIN_REQUEST",
data
}
}
//동기
const loginSuccess= (data)=>{
return{
type: "LOGIN_SUCCESS",
data
}
}