Getting redux-json-api set up requires 4 steps which we will cover here.
- Install through npm
- Add redux-json-api reducer to api namespace
- Add required middleware to store
- Configure API endpoints and access token
$ npm install redux-json-api --save
The current version of redux-json-api assumes that it's reducer reduced on to your root reducer under the namespace api.
You can achieve this by using combineReducers from Redux:
// rootReducer.js
import { combineReducers } from 'redux';
import { reducer as api } from 'redux-json-api';
export default combineReducers({
api
});
Since most of redux-json-api's are async it is required to configure your store with the redux-thunk middleware. Please see their docs for installation instructions.
As redux-json-api will automatically make requests to your API, it requires to know about API host, root path and any headers, such as an access token.
By default, without the host and root path being set, all requests will be made to the current host at root (example: /tasks
) with the following headers:
headers: {
'Content-Type': 'application/vnd.api+json',
Accept: 'application/vnd.api+json'
}
To change any of the defaults, the appropriate set
methods should be dispatched before dispatching any CRUD actions.
Dispatch the returned action to set endpoint hostname. It requires one argument, which is a full hostname including protocol.
dispatch(setEndpointHost('https://api.my-server'));
Dispatch the returned action to configure endpoint root path. It requires one argument.
dispatch(setEndpointPath('/v1'));
Host and path will be concatenated without any validation. Be aware of missing slashes. This will cause an error, due to a missing forward slash:
dispatch(setEndpointHost('https://api.my-server'));
dispatch(setEndpointPath('v1'));
// => https://api.my-serverv1
Dispatch this action to configure an access token to include in all requests.
This will in turn dispatch a setHeader request, setting the header up as
Authorization: Bearer <accessToken>
.
Dispatch this action to configure any headers to be included in all requests. The singular 'setHeader' action will merge in the given header(s).
Dispatch this action to completely reset the headers, removing all defaults.
The equivalent of dispatch(setAccessToken('myToken123'))
is:
dispatch(setHeaders({
Authorization: `Bearer myToken123`,
'Content-Type': 'application/vnd.api+json',
Accept: 'application/vnd.api+json'
}));