Coder Social home page Coder Social logo

ptzagk / redux-saga Goto Github PK

View Code? Open in Web Editor NEW

This project forked from redux-saga/redux-saga

0.0 1.0 0.0 4 MB

An alternative side effect model for Redux apps

Home Page: http://yelouafi.github.io/redux-saga/

License: MIT License

JavaScript 98.16% TypeScript 1.84%

redux-saga's Introduction

redux-saga

Join the chat at https://gitter.im/yelouafi/redux-saga npm version

redux-saga is a library that aims to make side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better.

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 them here are some introductory links) By doing so, these asynchronous flows look like your standard synchronous JavaScript code. (kind of like async/await, but generators have a few more awesome features we need)

You might've used redux-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 --save redux-saga

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

Usage Example

Suppose we have an 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.)

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

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

sagas.js

import { takeEvery, takeLatest } from 'redux-saga'
import { call, put } 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;

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

main.js

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

Documentation

There is also a chinese version of the docs website thanks @superRaytin (You may check the referenced version of redux-saga)

Using umd build in the browser

There is also a umd build of redux-saga available in the dist/ folder. When using the umd build redux-saga is available as ReduxSaga in the window object.

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

The following builds are available:

Important! If the browser you are targeting doesn't support ES2015 generators, you must provide a valid polyfill, such as the one provided by babel. The polyfill must be imported before redux-saga:

import 'babel-polyfill'
// then
import sagaMiddleware from 'redux-saga'

Building examples from sources

$ git clone https://github.com/yelouafi/redux-saga.git
$ cd redux-saga
$ npm install
$ npm test

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 in index.html.

To launch the example, just open index.html in your browser.

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

counter

Demo using webpack and high-level API takeEvery.

$ 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

redux-saga's People

Contributors

yelouafi avatar coryhouse avatar djebbz avatar bit3725 avatar jihchi avatar cef62 avatar tangruixing avatar aikoven avatar baisang avatar jscinoz avatar billyjanitsch avatar gpx avatar mxstbr avatar sorrycc avatar kuy avatar yjcxy12 avatar secobarbital avatar gaearon avatar chentsulin avatar fasterthanlime avatar superraytin avatar slorber avatar paul42 avatar monochrome-yeh avatar michaelandersoncampingworld avatar stipsan avatar prashaantt avatar pke avatar jhsu avatar sompylasar avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.