รายละเอียดสำหรับเรียนรู้ React ปี 2020-2023 โดยโค้ชพล ดูหลักสูตรได้ที่ https://www.nextflow.in.th/react-training
npm i redux-saga
หรือ
yarn add redux-saga
สร้างไฟล์ src/redux/sagas/sagas.js
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
export function* helloSaga() {
console.log('Hi Sagas');
}
function
เป็น function*
ทำให้ฟังก์ชั่นนี้ถูกเรียกว่า Generator functionyield
ซึ่งจะเป็นกลไกสำคัญของการใช้งาน Sagaเดี๋ยวจะมีตัวอย่าง ตอนนี้ setup ก่อนแล้วกัน
เปิดไฟล์ src/redux/store.js
redux saga ก็จะมี middleware เหมือน library อื่นๆ เราสามารถสร้าง และเพิ่มลงใน store ได้
เพราะเราต้องการให้ Store ส่งผ่าน Action เข้า redux saga
import createSagaMiddleware from 'redux-saga'
//...
const sagaMiddleware = createSagaMiddleware()
//...
const store = createStore(
createRootReducer(history),
compose(
applyMiddleware(
routerMiddleware(history),
sagaMiddleware,
logger
),
),
จากนั้นให้เราเรียกใช้ sagaMiddleware รัน saga module ที่เราเขียนไว้ก่อนหน้านี้
import { helloSaga } from './sagas/sagas';
//...
sagaMiddleware.run(helloSaga)
src/redux/store.js
import { createStore, applyMiddleware, compose } from 'redux';
import { logger } from 'redux-logger';
import { routerMiddleware } from 'connected-react-router'
import { createBrowserHistory } from 'history'
import createRootReducer from "./root.reducer";
import createSagaMiddleware from 'redux-saga'
import { helloSaga } from './sagas/sagas';
const sagaMiddleware = createSagaMiddleware()
export const history = createBrowserHistory()
export default function configureStore() {
const store = createStore(
createRootReducer(history),
compose(
applyMiddleware(
routerMiddleware(history),
sagaMiddleware,
logger
),
),
);
sagaMiddleware.run(helloSaga)
return store;
}