redux-fetch-duck
Simple and flexible API for creating a redux duck to manage a single fetch request, features loading and error states.
Instalation
It requires redux and thunk middleware.
$ yarn add redux-fetch-duck redux redux-thunk
Example
Simple usage
You can create a single file module in your project
// users.js; // This function is in charge of fetching the data.// It must return a promiseconst callApi = ;// Selectors funcions depends on wich library is doing the request. They are optional.const dataSelector = resdata;const errorSelector = errbodymessage; // This functions returns the thunk ready to be disptched.const getUsers = // creates the duck reducer. 'users';
Combine the new duck reducer
// rootReducer.js;; users
This generate the state initial state
users: data: null loading: false error: null
Finally dispatch the thunk if you want to fetch de data
;; Component { if !thispropsusers thisprops; } { const loading users error = thisprops; if loading return <div>Loading ...</div>; if error return <div>Cant fethc data error: error</div> return <div> users </div> } loading: stateusersloading error: stateuserserror users: stateusersdataContainer;
Extend your reducer
If you need a more complex state for your fetching resource you can import the types and action creators.
// users.js; // return an object with keys request, success, failureconst fetchTypes = ; // this reducer will count the number of calls to the APIconst calls = { }; // pass the reducer to be combined, it calls combineReducer under the hood.'users' calls
The new initial state will be
users: data: null loading: false error: null calls: 0
API
You can find the api documentation here
Motivation
This module aims to reduce the boilerplate generated when you adopt this common pattern in Redux based apps.
Test
The test suite requires Jest, clone the repo, install the dependencies and then run the tests.
$ yarn$ yarn test
Contribution
Feel free to create an Issue or even a pull request. You can email me at ivanwolf15@gmail.com. I'd love to hear your feedback.
License
MIT