dispatch
와 getState
를 파라미터로 받아와야하는데, thunk가 이 함수를 만들어준다$ npm i redux-thunk
function createThunkMiddleware(extraArgument){
return ({dispatch,getState})=> (next) => (action) => {
if(typeof action === 'function'){
return action(dispatch, getState, extraArgument)
}
return next(action);
}
}
const thunk = createThunkMiddleware()
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
$ npm i redux-saga
const sagaMiddleware = createSagaMiddleware();
...
composeWithDevTools(applyMiddleware(sagaMiddleware))
...
sagaMiddleware.run(rootSaga)
// sagas/index.js -- rootsaga
import {all, fork} from 'redux-saga/effects'
import postSaga from './post'
import userSaga from './user'
export default function * rootSaga(){
yield all([
fork(userSaga),
fork(postSaga)
])
}
// sagas/user.js
import {all,fork} from 'redux-saga'
function* logIn(){
try{
//const result = yield call(loginAPI)
yield put({
type:'LOG_IN_SUCCSS',
data:result.data
})
}catch(err){
yield put({
type:'LOG_IN_FAILURE',
data:err.response.data
});
}
}
function loginAPI(){
return axios.post('/api/login')
}
function* logOut(){
try {
const result = yield call(login)
} catch (error) {
}
}
function* watchLogin(){
yield take('LOG_IN_REQUEST',logIn);
}
function* watchLogout(){
yield take('LOG_OUT_REQUEST');
}
export default function* userSaga(){
yield all([
fork(watchLogIn),
fork(watchLogOut)
])
}
import {all, call, fork, put, take} from 'redux-saga/effects'
function loginAPI(){
return axios.post('/api/login')
}
function* logIn(){
try{
const result = yield call(loginAPI)
yield put({
type:'LOG_IN_SUCCSS',
data:result.data
})
}catch(err){
yield put({
type:'LOG_IN_FAILURE',
data:err.response.data
});
}
}
function* watchLogin(){
yield take('LOG_IN',logIn);
}
function* watchLogout(){
yield take('LOG_OUT');
}
function* watchAddPost(){
yield take('ADD_POST')
}
export default function * rootSaga(){
yield all([
call(watchLogin), //fork
call(watchLogout),
call(watchAddPost),
])
}
📑 reference