redux-deferred

0.1.0 • Public • Published

redux-deferred

Redux middleware for jQuery Deferred Object.

NPM

Preface

To create an AJAX request in jQuery is easy.

$.get('some.url',function(result){
  // do things with result
})

It is not known by everyone that all AJAX method in jQuery return an Deferred Object for you to use. So above code can be rewriten like this:

let deferredObject = $.get('some.url');
deferredObject.done(function(result){
  // do things with result
})

Using this middleware you can wrap the request into the payload of an action and dispatch it like any normal actions.

let action = {
   type:'LOAD_SOME',
   payload: deferredObject
}
 
store.dispatch(action);

Since Deferred is often async, the action wrapping it will not be dispatched until it is resolved or rejected.

And when it does, the action will be really dispatched with payload changed to the result value of the deferred.

(state={},action)=>{
  switch(action.type){
    case 'LOAD_SOME':
      return Object.assign({},state,{
        data:action.payload
      });
   default:
      return state;
  }
}

Error handling

If the request fail, your can get error detail infomation in action's payload property. While action's error property equals true.

(state={},action)=>{
  switch(action.type){
    case 'LOAD_SOME':
      if(action.error){
        return Object.assign({},state,{
          error:action.payload
        });
      }else{
        return Object.assign({},state,{
          data:action.payload
        });
      }
   default:
      return state;
  }
}

That's all. The redux-deferred core code is below 30 lines. And heavily inspired by redux-promise.

Usage

Install

npm install redux-deferred

ES6

import DeferredMiddleware from 'redux-deferred';
let reducers= YOUR_REDUCER_DEFINITION;
let store = createStore(reducers,applyMiddleware(DeferredMiddleware));

Reference

Example

redux-deferred

License

MIT

Package Sidebar

Install

npm i redux-deferred

Weekly Downloads

5

Version

0.1.0

License

MIT

Last publish

Collaborators

  • wyvernnot