sagas/rootSage.js
import {delay} from 'redux-saga';
import {all} from 'redux-saga/effects';
- effect là hàm kết nối redux-saga vào reducer
- all là một redux saga effect dùng để chạy nhiều saga cùng 1 lúc
import { sayHello, watchIncrement, watchDecrement } from './counterSaga'; /*import 3 saga watch function*/
export default function* rootSaga(){
yield all([
sayHello(),
watchIncrement(),
watchDecrement()
]); //nhiều saga
}
- yield: chạy tuần tự, saga1 chạy > saga2 > saga3 ...
- takeEvery: theo dõi 1 action nào đó thay đổi thì nó sẽ chui vào 1 cái saga nào đấy để xử lý
- takeLastest: lấy 1 action mới nhất, tay bấm liên tục gọi action thì lấy cái mới nhất
- các hàm lấy dữ liệu trên server ta luôn để try catch vì không biết thực sự thành công hay thất bại
function* fnFetchMovies(){
try{
const receiveMovies = yield ApiGetMovies();
yield put(FETCH_MOVIES_SUCCESSED, receiveMovies: receiveMovies); /*DISPATCH nếu thành công*/
}catch(error){
yield put(FETCH_MOVIES_ERROR, error);
}
}
export function* fnFetchMovies(){
yield takeLastest(FETCH_MOVIES, fnFetchMovies);
}
function* ApiGetMovies(){
const response = yield fetch(url, {
method: 'GET',
headers: {},
body: ''
});
let movies = yield.status == 200? JSON.parse(response.data):[];
return movies;
}
sagas/counterSaga.js
export function* watchIncrement(){
yield takeEvery(INCREMENT,fnIncrement); /*khi action INCREMENT thay đổi thì hàm saga fnIncrement sẽ được gọi*/
}
function* fnIncrement(){
console.log("increment");
}
//tương tự cho decrement
export function* watchDecrement(){
yield takeEvery(DECREMENT,fnDecrement); /*khi action INCREMENT thay đổi thì hàm saga fnIncrement sẽ được gọi*/
}
function* fnDecrement(){
console.log("decrement");
}
index.js
import {createStore, applyMiddleware} from 'redux';
import { Provider } from 'react-redux';
import allReducers from './reducers';
import createSagaMiddleware from 'redux-saga';
import rootSaga from './sagas/rootSaga';
import counterContainer from './containers/counterContainer';
//1.
const sagaMiddleware = createSagaMiddleware();
//2. store
let store = createStore(allReducers, applyMiddleware(sagaMiddleware));
//3.
const App = ()=>(
<Provider store = {store}>
<counterContainer/>
</Provider>
);
//4. run saga chạy nhiều saga cùng 1 lúc
sagaMiddleware.run(rootSaga);