Redux Data Loader
Loads async data for Redux apps focusing on preventing duplicated requests and dealing with async dependencies.
Deeply inspired by alt Data Souces API, also inspired by redux-saga.
Instead of using redux-thunk, it handles wrapped actions and sideload async data. It also caches data requests for a while in order to prevent duplicated requests.
Installation
npm install redux-dataloader --save
Usage
1. Define actions and update the request action with load()
userActions.js
; const FETCH_USER_REQUEST = 'myapp/user/FETCH_USER/REQUEST';const FETCH_USER_SUCCESS = 'myapp/user/FETCH_USER/SUCCESS';const FETCH_USER_FAILURE = 'myapp/user/FETCH_USER/FAILURE'; { // use `load` to wrap a request action, load() returns a Promise return } { // ...} { // ...}
2. Create a data loader
dataloaders.js
; ; const userLoader = ; userLoader;
3. Register middleware
configureStore.js
;;;;; const fetcher = xhrPath: '/api'; // create middleware, you can add extra arguments to data loader contextconst dataLoaderMiddleware = ; const store = // ...
4. Use it for your application
Then, just use it in your application. The following is an example that combined with redial for isomorphic use.
;;;; // the router location is: /:username/:articleId// Data dependency: user <= article <= articleSkin { try // 1. Fetch user const username = paramsusername; await ; // wait for response // 2. Fetch article by userId and articleId, you may use useId for authentication const user = userusersusername; if !user throw `user_not_found: `; const articleId = paramsarticleId; await ; // 3. Fetch article skin by articleId const article = articlearticlesarticleId; if !article throw `article_not_found: `; await ; catch err // ... } { // ...} @@Component // ...
You can also write fetchData()
with Promise:
{ return Promise}
Documentation
License
MIT