メインコンテンツにスキップ

はじめに

インストール

$ npm install redux-saga

または

$ yarn add redux-saga

あるいは、提供されているUMDビルドをHTMLページの<script>タグで直接使用することもできます。このセクションを参照してください。

使用例

ボタンがクリックされたときに、リモートサーバーからユーザーデータを取得するUIがあるとします。(簡潔にするため、アクションをトリガーするコードのみを示します。)

class UserComponent extends React.Component {
...
onSomeButtonClicked() {
const { userId, dispatch } = this.props
dispatch({type: 'USER_FETCH_REQUESTED', payload: {userId}})
}
...
}

コンポーネントは、プレーンオブジェクトアクションをストアにディスパッチします。すべてのUSER_FETCH_REQUESTEDアクションを監視し、ユーザーデータを取得するためのAPI呼び出しをトリガーするSagaを作成します。

sagas.js

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

// worker Saga: will be fired on USER_FETCH_REQUESTED actions
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 })
}
}

/*
Starts fetchUser on each dispatched `USER_FETCH_REQUESTED` action.
Allows concurrent fetches of user.
*/
function* mySaga() {
yield takeEvery('USER_FETCH_REQUESTED', fetchUser)
}

/*
Alternatively you may use takeLatest.

Does not allow concurrent fetches of user. If "USER_FETCH_REQUESTED" gets
dispatched while a fetch is already pending, that pending fetch is cancelled
and only the latest one will be run.
*/
function* mySaga() {
yield takeLatest('USER_FETCH_REQUESTED', fetchUser)
}

export default mySaga

Sagaを実行するには、redux-sagaミドルウェアを使用してReduxストアに接続する必要があります。

main.js

import { configureStore } from '@reduxjs/toolkit'
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 = configureStore({
reducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(sagaMiddleware),
})

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

// render the application

ブラウザでのUMDビルドの使用

dist/フォルダには、redux-sagaの**UMD**ビルドもあります。umdビルドを使用する場合、`redux-saga`はウィンドウオブジェクトで`ReduxSaga`として使用できます。これにより、ES6の`import`構文を使用せずに、次のようにSagaミドルウェアを作成できます。

var sagaMiddleware = ReduxSaga.default()

UMDバージョンは、WebpackまたはBrowserifyを使用しない場合に便利です。unpkgから直接アクセスできます。

以下のビルドが利用可能です

**重要!**ターゲットとするブラウザが_ES2015ジェネレーター_をサポートしていない場合は、それらをトランスパイル(例:babelプラグインを使用)し、ここにあるような有効なランタイムを提供する必要があります。ランタイムは**redux-saga**の前にインポートする必要があります

import 'regenerator-runtime/runtime'
// then
import sagaMiddleware from 'redux-saga'