Giter Club home page Giter Club logo

redux-promises's Introduction

redux-promises

NPM Version Build Status

Promise based middleware for Redux to deal with asynchronous actions. redux-promises is backwards compatible with redux-thunk.

It works by collecting any promise returned by action thunks, to keep track whether or not these promises are pending or not. When there are no pending promises the state is idle.

Installation

npm install --save redux-promises

You need to use the redux-promises middleware and reducer.

import { combineReducers, applyMiddleware, createStore } from 'redux';
import { reducer as idleReducer, createMiddleware } from 'redux-promises';

const reducer = combineReducers({
  idle: idleReducer,
  // ...other reducers
});

const promisesMiddleware = createMiddleware();
const store = applyMiddleware(promisesMiddleware)(createStore)(reducer);

You can then call the function ensureIdleState which returns a promise that resolves as soon as there are no more pending promises and the state is idle.

import { ensureIdleState } from 'redux-promises';

ensureIdleState(store).then(() => {
  // do awesome stuff knowing all promises (if any) are resolved (or rejected)
});

If you don’t want to store redux-promises state under the idle key, you need to pass a function to select state to ensureIdleState.

ensureIdleState(store, state => state.myIdleKey).then(() => {/**/});

Why?

For server-side rendering in React you need to know when all asynchronous requests are either resolved or rejected. As a bonus you get thunks for free!

Example 1

A simple example, working code can be found in the examples/simple directory.

import { createStore, applyMiddleware } from 'redux';
import { createMiddleware, ensureIdleState } from 'redux-promises';
import reducers from './reducers'; // should include `redux-promises` reducer

const promisesMiddleware = createMiddleware();
const store = applyMiddleware(promisesMiddleware)(createStore)(reducers);

// Action creator that returns a thunk that returns a promise
const fetchData = (url) => (dispatch) => {
  dispatch({ type: 'FETCH_REQUEST' });

  return fetch(url).then(
    (result) => dispatch({ type: 'FETCH_SUCCESS', result }),
    (error) => dispatch({ type: 'FETCH_FAILURE', error })
  );
};

// Somewhere else in your application there are some dispatches
store.dispatch(fetchData('http://api.example.com/some/resouce'));
store.dispatch(fetchData('http://api.example.com/another/resouce'));

// Now we wait till all required data has been fetched
ensureIdleState(store).then(() => {
  // Fetching all data complete
});

Example 2

In the previous example if you write a lot of action creators this way you might want a helper function to create them for you. Again working code can be found in the examples/thunk-creator directory.

Credit for this syntax (and the previous one for that matter) goes to Dan Abramov.

const thunkCreator = (action) => {
  const { types, promise, ...rest } = action;
  const [ REQUESTED, RESOLVED, REJECTED ] = types;

  return (dispatch) => {
    dispatch({ ...rest, type: REQUESTED });

    return promise.then(
      (result) => dispatch({ ...rest, type: RESOLVED, result }),
      (error) => dispatch({ ...rest, type: REJECTED, error })
    );
  };
};

// Action creator that returns a thunk that returns a promise
const fetchData = (url) => thunkCreator({
  types: ['FETCH_REQUEST', 'FETCH_SUCCESS', 'FETCH_FAILURE'],
  promise: fetch(url)
});

redux-promises's People

Contributors

crocodillon avatar

Watchers

James Cloos avatar  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.