Awesome
redux-deferred
Deprecated
This project is depracated and no longger maintained since jQuery Deferred has been updated to be compatible with Promises/A+ and ES2015 (a.k.a ES6) Promise Use redux-promise instead
Redux middleware for jQuery Deferred Object.
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
})
For this middleware to work you MUST
wrap the deferredObject into the payload
of an action and then dispatch it.
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
License
MIT