Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

An alternative side effect model for Redux apps

License

MIT, Unknown licenses found

Licenses found

MIT
LICENSE
Unknown
LICENSE-logo.md
NotificationsYou must be signed in to change notification settings

redux-saga/redux-saga

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Redux Logo Landscape

redux-saga

npm versionCDNJSnpmDiscord ShieldOpenCollectiveOpenCollective

redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, easy to test, and better at handling failures.

The mental model is that a saga is like a separate thread in your application that's solely responsible for side effects.redux-saga is a redux middleware, which means this thread can be started, paused and cancelled from the main application with normal redux actions, it has access to the full redux application state and it can dispatch redux actions as well.

It uses an ES6 feature called Generators to make those asynchronous flows easy to read, write and test.(if you're not familiar with themhere are some introductory links) By doing so, these asynchronous flows look like your standard synchronous JavaScript code. (kind of likeasync/await, but generators have a few more awesome features we need)

You might've usedredux-thunk before to handle your data fetching. Contrary to redux thunk, you don't end up in callback hell, you can test your asynchronous flows easily and your actions stay pure.

Getting started

Install

$ npm install redux-saga

or

$ yarn add redux-saga

Alternatively, you may use the provided UMD builds directly in the<script> tag of an HTML page. Seethis section.

Usage Example

Suppose we have a UI to fetch some user data from a remote server when a button is clicked. (For brevity, we'll just show the action triggering code.)

classUserComponentextendsReact.Component{  ...onSomeButtonClicked(){const{ userId, dispatch}=this.propsdispatch({type:'USER_FETCH_REQUESTED',payload:{userId}})}  ...}

The Component dispatches a plain Object action to the Store. We'll create a Saga that watches for allUSER_FETCH_REQUESTED actions and triggers an API call to fetch the user data.

sagas.js

import{call,put,takeEvery,takeLatest}from'redux-saga/effects'importApifrom'...'// worker Saga: will be fired on USER_FETCH_REQUESTED actionsfunction*fetchUser(action){try{constuser=yieldcall(Api.fetchUser,action.payload.userId)yieldput({type:'USER_FETCH_SUCCEEDED',user:user})}catch(e){yieldput({type:'USER_FETCH_FAILED',message:e.message})}}/*  Starts fetchUser on each dispatched `USER_FETCH_REQUESTED` action.  Allows concurrent fetches of user.*/function*mySaga(){yieldtakeEvery('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(){yieldtakeLatest('USER_FETCH_REQUESTED',fetchUser)}exportdefaultmySaga

To run our Saga, we'll have to connect it to the Redux Store using theredux-saga middleware.

main.js

import{createStore,applyMiddleware}from'redux'importcreateSagaMiddlewarefrom'redux-saga'importreducerfrom'./reducers'importmySagafrom'./sagas'// create the saga middlewareconstsagaMiddleware=createSagaMiddleware()// mount it on the Storeconststore=createStore(reducer,applyMiddleware(sagaMiddleware))// then run the sagasagaMiddleware.run(mySaga)// render the application

Documentation

Translation

Using umd build in the browser

There is also aumd build ofredux-saga available in thedist/ folder. When using the umd buildredux-saga is available asReduxSaga in the window object. This enables you to create Saga middleware without using ES6import syntax like this:

varsagaMiddleware=ReduxSaga.default()

The umd version is useful if you don't use Webpack or Browserify. You can access it directly fromunpkg.

The following builds are available:

Important! If the browser you are targeting doesn't supportES2015 generators, you must transpile them (i.e. withbabel plugin) and provide a valid runtime, such asthe one here. The runtime must be imported beforeredux-saga:

import'regenerator-runtime/runtime'// thenimportsagaMiddlewarefrom'redux-saga'

Building examples from sources

$ git clone https://github.com/redux-saga/redux-saga.git$cd redux-saga$ yarn$ npmtest

Below are the examples ported (so far) from the Redux repos.

Counter examples

There are three counter examples.

counter-vanilla

Demo using vanilla JavaScript and UMD builds. All source is inlined inindex.html.

To launch the example, openindex.html in your browser.

Important: your browser must support Generators. Latest versions of Chrome/Firefox/Edge are suitable.

counter

Demo usingwebpack and high-level APItakeEvery.

$ npm run counter# test sample for the generator$ npm run test-counter

cancellable-counter

Demo using low-level API to demonstrate task cancellation.

$ npm run cancellable-counter

Shopping Cart example

$ npm run shop# test sample for the generator$ npm run test-shop

async example

$ npm run async# test sample for the generators$ npm run test-async

real-world example (with webpack hot reloading)

$ npm run real-world# sorry, no tests yet

TypeScript

Redux-Saga with TypeScript requiresDOM.Iterable orES2015.Iterable. If yourtarget isES6, you are likely already set, however, forES5, you will need to add it yourself.Check yourtsconfig.json file, and the officialcompiler options documentation.

Logo

You can find the official Redux-Saga logo with different flavors in thelogo directory.

Redux Saga chooses generators overasync/await

Afewissues have been raised asking whether Redux saga plans to useasync/await syntax instead of generators.

We will continue to usegenerators. The primary mechanism ofasync/await is Promises and it is very difficult to retain the scheduling simplicity and semantics of existing Saga concepts using Promises.async/await simply don't allow for certain things - like i.e. cancellation. With generators we have full power over how & when effects are executed.

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]

License

Copyright (c) 2015 Yassine Elouafi.

Licensed under The MIT License (MIT).


[8]ページ先頭

©2009-2025 Movatter.jp