在建立 Saga 之前,我們要先建立對應的 action
,以前一篇 EDIT_USERNAME
為例,當我們發出一個任務後,就會有 SUCCESS
和 ERROR
。如此一來就會有三個 actionType
:
再來建立一個變更 username 的 action
const export editUsernameAction = payload => ({
type: 'EDIT_USERNAME',
payload
});
要建立一個 Saga Function 要使用 general function
,如下:
api
export function editUserApi (payload) {
return fetch('http://api.com/path/user', {
method: 'PUT',
body: JSON.stringfy(payload)
});
}
// 定義成功的 Action
const editSuccessAction = payload => ({
type: 'EDIT_USERNAME_SUCCESS',
payload,
});
// 定義失敗的 Action
const editErrorAction = payload => ({
type: 'EDIT_USERNAME_ERROR',
payload,
})
export function* editUsernameSaga ({ payload }) {
try {
// 發一個 api 請求
const data = yield call(editUserApi, payload);
const nextAction = data.success
? editSuccessAction
: editErrorAction;
yield put(nextAction(payload));
} catch(error) {
yield put(editErrorAction(error));
}
}
建立好 Saga 之後,要監聽 Saga,在 ~/src/sagas/watcher.js
加入:
import { editUsernameSaga } from './userSagas';
function* watchEditUsernameSaga() {
yield takeLatest("EDIT_USERNAME", editUsernameSaga);
}
export default watchEditUsernameSaga;
import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
const configureStore = () => {
const sagaMiddleware = createSagaMiddleware({});
const middlewares = [ sagaMiddleware ]; // 這邊弄成一個陣列可以隨時擴充
const store = createStore(
rootReducer,
compose(applyMiddleware(...middlewares))
);
return store;
}
const store = configureStore();
export default store;