iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
Modern Web

以 React 為主的那些前端事系列 第 25

Day 25 - redux-saga 文件範例

Q_Q 沒學完啦

Redux-saga 範例

import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'

import reducer from './reducers'
import mySaga from './sagas'

// create the saga middleware
const sagaMiddleware = createSagaMiddleware()
// mount it on the Store
const store = createStore(
  reducer,
  applyMiddleware(sagaMiddleware)
)

// then run the saga
sagaMiddleware.run(mySaga)

// render the application

sagas.js

import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...'

// 工作的 Saga:當 action 是 USER_FETCH_REQUESTED 時被觸發
function* fetchUser(action) {
   try {
      const user = yield call(Api.fetchUser, action.payload.userId);
      yield put({type: "USER_FETCH_SUCCEEDED", user: user});
   } catch (e) {
      yield put({type: "USER_FETCH_FAILED", message: e.message});
   }
}

/*
  在每次 dispatch `USER_FETCH_REQUESTED` action 時,啟動 fetchUser。
  允許同時取得使用者。
*/
function* mySaga() {
  yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}

/*
  另外你也可以使用 takeLatest。

  但不允許同時取得使用者。當一個 fetch 已經在 pending 時,如果取得 dispatch「USER_FETCH_REQUESTED」,
  正在等待的 fetch 會被取消,只執行最新的發出的 USER_FETCH_REQUESTED。
*/
function* mySaga() {
  yield takeLatest("USER_FETCH_REQUESTED", fetchUser);
}

export default mySaga;

REF

https://neighborhood999.github.io/redux-saga/


上一篇
Day 24 - redux-saga 用到 Generators~
下一篇
Day 26 - styled-components 筆記1
系列文
以 React 為主的那些前端事30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言