react-redux-api-tools
This project provides a middleware and a request helper to streamline react-redux data fetching.
Installing
Just run npm install --save react-redux-api-tools
and you're good to go.
fetchFromApi
helper
Using the One of the problems of using the default fetch implementation is that it does not reject if the status code is 4xx.
It makes our reducers not exactly semantic, since a 400 Bad Request will be interpreted as a successful request.
For that case, we provide the fetchFromApi
helper, which overrides fetch to reject on anything with status equal or above 400.
To use it, import it and use it on the apiCallFunction
key, inside your actions:
/store/actions.js
; // we declare a new action called createProduct that will POST to the backendconst createProduct = { // first, we consolidate the request data inside a dict. // we follow the Request object API // https://developer.mozilla.org/en-US/docs/Web/API/Request // by default, the method is 'GET' and we use "content-type: application/json" headers, // but you may overwrite the headers as needed const requestData = method: 'POST' body: JSON return types: request: 'CREATE_PRODUCTS' success: 'CREATE_PRODUCTS_SUCCESS' failure: 'CREATE_PRODUCTS_FAILURE' // here is where we use it ;}
Using the middleware
Middleware capabilities
The middleware bundles three actions (request
, success
and failure
) into one action call.
Let me show you with code. This is what a request action would look like when you're using the middleware:
// we declare a new action called fetchProducts that will fetch dataconst fetchProducts = { return // instead of returning the key 'type' with one action type, // we return three, one for each step of the request // inside the 'types' key types: request: 'FETCH_PRODUCTS' success: 'FETCH_PRODUCTS_SUCCESS' failure: 'FETCH_PRODUCTS_FAILURE' // we also declare a function that will implement the proper request ;}
That will:
- trigger the
FETCH_PRODUCTS
reducer on request start; - trigger
FETCH_PRODUCTS_SUCCESS
if the request succeeds; - trigger
FETCH_PRODUCTS_FAILURE
if it doesn't.
Making multiple requests at the same time
If you want to make multiple requests in the same call, instead of returning a single fetchFromApi
call, you may use Promise.all
passing a list of fetchFromApi
calls:
const fetchMultipleProducts = { return types: request: 'FETCH_MULTIPLE_PRODUCTS' success: 'FETCH_MULTIPLE_PRODUCTS_SUCCESS' failure: 'FETCH_MULTIPLE_PRODUCTS_FAILURE' Promiseall ;}
When all of them are successful, the 'FETCH_MULTIPLE_PRODUCTS_SUCCESS'
reducer will be called with a list of Response
objects. When one of them fails, the 'FETCH_MULTIPLE_PRODUCTS_FAILURE'
will be triggered passing the Error
instance (most probably a TypeError: Failed to fetch
error).
Setup
Assuming you've already installed react and redux, to use it, you'll need to install redux-thunk
first:
npm install --save redux-thunk
Then, we need to apply the middleware when the application starts:
App.js
// on your app setup:;;;// we import the applyMiddleware function from redux// and the apiMiddleware from our tools;; ;; // then, when we create the base store, we apply the middlewareconst store = ; Component { return <Provider store=store> <Routes /> </Provider> }
Then, every time you want to create an action that calls an api, you just need to pass the three types and an api call function as we have stated above:
/store/actions.js
// we declare a new action called fetchProducts that will fetch dataconst fetchProducts = { return // instead of returning the key 'type' with one action type, // we return three, one for each step of the request // inside the 'types' key types: request: 'FETCH_PRODUCTS' success: 'FETCH_PRODUCTS_SUCCESS' failure: 'FETCH_PRODUCTS_FAILURE' // we also declare a function that will implement the proper request // there is an optional callback so we can stop a request if we don't need to refetch the data // it works both for request and default actions { return !appStateproductsitemslength } // and you may as well pass some extra data, if needed extraData: brand anything: 'could go here, and it will be available on the action.extraData attribute' ;}
On the reducers side, nothing much changes. We pass the response
(always) and error
(when the request fails) objects to the action, so we can get the response/error data on the reducers:
/store/reducers.js
const productReducer = { }
Finally, on the component, you'll just need to bind it with redux and the code will be so clean:
/components/ProductsList.js
import React from 'react';import connect from 'react-redux'import fetchProducts from '../store/actions'; Component { // we just need to dispatch it. ONCE. no redux management here. thisprops; } { const isLoading error items = thisprops; if isLoading return <h1>Loading...</h1> if error return <p ='error'>JSON</p> return <React.Fragment> <h1>Products List</h1> items </React.Fragment> ; } // here, we bind the redux state as component props:const mapStateToProps = state isLoading: stateisLoading items: stateitems error: stateerror;// and bind the action dispatch to a prop as well:const mapDispatchToProps = dispatch ; // and connect it to redux :)mapStateToProps mapDispatchToPropsProductsList;
Contributing
Don't hesitate to open an issue for bugs!
But if you would like a new feature, it would be nice to discuss it before accepting PRs. We reserve ourselves the right to reject a feature that was not discussed or that will impact the code in a meaningful way. In that case, open an issue so we can discuss. Thanks. <3