redux-rx-http
TODO: Update Readme for 1.0
So, you like redux, you like RxJS, you're using redux-observable. You want to talk to APIs, and consume the side effects through epics, and you want a nice, simple way to do it. This library works by having a single API action where the side-effect actions (request, success, error, cancel) are passed in with the initial action in a clean, consistent way. Oh, and we have type definitions!
Important note: As of version 0.14, fetch is used internally. This means you will have to inject fetch as a dependency in your
createEpicMiddleware
function, e.g. isomorphic-fetch. Also, cancellation won't actually cancel the original request, it will just terminate the inner stream (so no further actions will be emitted).
Configuration
Configuration allows you to set the base URL and initial headers for all requests.
Because your base request configuration could be dynamic based on your application state, config is done as a function, with store.getState() as the primary argument.
For instance, say your authorisation token was acquired asyncronously and put in your store...
configure-store.ts
// ...imports...
Usage
To make a simple HTTP GET request, and then listen to the results...
actions.ts
// Action to fetch a potat from our API
epics.ts
// Simply take the request, and map it to some sort of UI action. .mapTo // Hide the spinner on done. .mapTo // Consume the results of loading our potato! .map // Handle erroneous potato fetch .map
More complex usage
Of course, simply getting a potato is simple, but each function takes a third argument of a relevant thing:
- Query params:
rxHttpGet
- Request body:
rxHttpPost
,rxHttpPut
,rxHttpPatch
- None:
rxHttpDelete
,rxHttpHead
And a final argument which is of type RxHttpRequestConfig
.
So a more complex usage could look something like this:
actions.ts
epics.ts
.map
I would advise against putting callbacks in args, as that entirely misses the point.
Cancellation
Because we're using observables, requests can be cancelled!
actions.ts
// Action to cancel said fetching
Filtering output actions
If for some utterly bizarre reason the amount of actions going through the redux store is a performance issue, you can filter both global and your local actions.
Global actions
Only generate success action:
rxHttpGet'https://potato.com/api', myActions, ,
This can be added to base request config, as with anything else
Specific actions
Only generate success action:
Simple!