Redux Request Status
Getting Started
Must use redux-thunk (or any custom middleware that provides the dispatch method to an action that is a funciton)
npm install --save redux-request-status
Motivation
Provide a Declarative, readable, easy to implement utility for handling asyncronous status changes. Typically, this will be an http request, but could be anything asyncronous action that returns a promise. Using redux-request-status
we're able to respond to 3 different actions by ( onRequest
, onSuccess
, or onError
) for a single action type.
// actions.js;; { return { ; }} { return ;}
// reducer.js;;; // just a shortcut helper to merge state... returns Object.assign({}, ...arguments); { }
Creating Asyncronous Actions Using Promises and Thunks
the function asyncActionCreator
will return a thunk (a function which deleys execution) for redux-thunk
to execute.
by dispatching the actionCreator getJoke
, redux-response-status
will dispatch one action for when the initial action was dispatched (this is where we would typically disable the UI or display a loader), and one action when the promise resolve/rejects.
; { return ;}
dispatching the result of asyncActionCreator()
will dispatch 2 actions; 1 immidiatly to handle the initial request and another on resolution or rejection of the promise passed to it.
the sucess action will assign the result of the promise to the data
key on the success action. the error action will assign the result of the rejected promise to the error
key on the error action. All three of these actions will also contain any additional properties on the object passed to asyncActionCreator
{ const category vulgarity = jokeOptions; return ;} store; /* 1st -- before making request { type: 'GET_JOKE [REQUEST]', jokeOptions: { category: 'military', vulgarity: 2 } } 2nd -- after promise resolves successfully { type: 'GET_JOKE [SUCCESS]', jokeOptions: { category: 'military', vulgarity: 2 }, data: { joke: 'How do you tell an officer to get lost?', punchline: 'Give him a compass and a map.' } } OR -- if the promose rejects { type: 'GET_JOKE [ERROR]', jokeOptions: { category: 'military', vulgarity: 2 }, error: { error_type: 'NO_JOKES_AVAILABLE', message: 'There are no jokes that match your query' } } */
Thanks
Thanks to @JevinAnderson for the feedback on the API.
License
MIT