import { createStore, applyMiddleware } from 'redux';import createSagaMiddleware from 'redux-saga';import rootReducer from './reducers';import rootSaga from './sagas';
// Khởi tạo saga middlewareconst sagaMiddleware = createSagaMiddleware();
// Tạo store với middleware sagaconst store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
// Chạy sagasagaMiddleware.run(rootSaga);
export default store;
import { takeEvery, put, call } from 'redux-saga/effects';import { FETCH_DATA, fetchDataSuccess, fetchDataFailure } from './actions';import api from './api';
function* fetchDataSaga(action) { try { const data = yield call(api.getData, action.payload); yield put(fetchDataSuccess(data)); } catch (error) { yield put(fetchDataFailure(error.message)); }}
function* watchFetchData() { yield takeEvery(FETCH_DATA, fetchDataSaga);}
export default function* rootSaga() { yield all([ watchFetchData(), // Các saga khác ]);}
Effect | Ý nghĩa | Ví dụ sử dụng |
---|---|---|
takeEvery | Lắng nghe mọi action | Xử lý đa tác vụ cùng loại |
takeLatest | Chỉ chạy tác vụ mới nhất | Hủy tác vụ cũ nếu có hành động mới |
call | Gọi hàm bất đồng bộ | Gọi API, các hàm trả về Promise |
put | Gửi action vào Redux | Dispatch kết quả hoặc lỗi |
all | Thực hiện song song | Kết hợp nhiều saga cùng lúc |
// actions.jsexport const FETCH_USERS = 'FETCH_USERS';export const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS';export const FETCH_USERS_FAILURE = 'FETCH_USERS_FAILURE';
export const fetchUsers = () => ({ type: FETCH_USERS });export const fetchUsersSuccess = users => ({ type: FETCH_USERS_SUCCESS, payload: users });export const fetchUsersFailure = error => ({ type: FETCH_USERS_FAILURE, payload: error });
// saga.jsimport { takeLatest, call, put } from 'redux-saga/effects';import { FETCH_USERS, fetchUsersSuccess, fetchUsersFailure } from './actions';import api from './api';
function* fetchUsersSaga() { try { const users = yield call(api.getUsers); yield put(fetchUsersSuccess(users)); } catch (error) { yield put(fetchUsersFailure(error.message)); }}
export default function* watchUserSagas() { yield takeLatest(FETCH_USERS, fetchUsersSaga);}
takeLatest
cho các tác vụ không cần chạy song song