Dead simple and ready-to-use store module for handling HTTP REST resources.
Generates types, actions and reducers for you to easily interact with any REST API.
Saves you from writing a lot of boilerplate code and ensures that your code stays DRY.
-
Requires redux-thunk to handle async actions.
-
Relies on fetch to perform HTTP requests. If you want to use this in environments without a builtin
fetch
implementation, you need to bring your own custom fetch polyfill.
npm i redux-rest-resource --save
-
Export created types, actions and reducers (eg. in
containers/Users/store/index.js
)import {createResource} from 'redux-rest-resource'; const hostUrl = 'https://api.mlab.com:443/api/1/databases/sandbox/collections'; const apiKey = 'xvDjirE9MCIi800xMxi4EKeTm8e9FUBR'; export const {types, actions, reducers} = createResource({ name: 'user', url: `${hostUrl}/users/:id?apiKey=${apiKey}` });
-
Import reducers in your store
import {combineReducers} from 'redux'; import {reducers as usersReducers} from 'containers/Users/store'; export default combineReducers({ users: usersReducers });
-
Use provided actions inside connected components
import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import {actions as userActions} from 'containers/Users/store'; import UserListItem from './UserListItem'; class UserList extends Component { componentDidMount() { const {actions} = this.props; actions.fetchUsers(); } render() { const {actions, users} = this.props; return ( <ul> {users.map(user => <UserListItem key={user.id} user={user} {...actions} />)} </ul> ); } } export default connect( // mapStateToProps state => ({users: state.users.items}), // mapDispatchToProps dispatch => ({ actions: bindActionCreators({...userActions}, dispatch) }) )(UserList);
types == {
"CREATE_USER": "@@resource/USER/CREATE",
"FETCH_USERS": "@@resource/USER/FETCH",
"GET_USER": "@@resource/USER/GET",
"UPDATE_USER": "@@resource/USER/UPDATE",
"DELETE_USER": "@@resource/USER/DELETE"
}
Object.keys(actions) == [
"createUser",
"fetchUsers",
"getUser",
"updateUser",
"deleteUser"
]
Every REST action creator will dispatch two actions, based on the Promise state:
// first
{type: '@@resource/USER/FETCH', status: 'pending', context}
// then
{type: '@@resource/USER/FETCH', status: 'resolved', context, body, receivedAt}
// or (catch)
{type: '@@resource/USER/FETCH', status: 'rejected', context, err, receivedAt}
You can find more information in src/actions
import {initialState} from 'redux-rest-resource';
initialState == {
// FETCH props
items: [],
isFetching: false,
lastUpdated: 0,
didInvalidate: true,
// GET props
item: null,
isFetchingItem: false,
lastUpdatedItem: 0,
didInvalidateItem: true,
// CREATE props
isCreating: false,
// UPDATE props
isUpdating: false,
// DELETE props
isDeleting: false
};
Option | Type | Description |
---|---|---|
name | String | Actual name of the resource (required) |
url | Function/String | Actual url of the resource (required) |
pluralName | String | Plural name of the resource (optional) |
actions | Object | Action extra options, merged with defaults (optional) |
credentials | String | Credentials option according to Fetch polyfill doc for sending cookies (optional) |
Option | Type | Description |
---|---|---|
method | Function/String | Method used by fetch (required) |
headers | Function/Object | Custom request headers (optional) |
isArray | Function/Boolean | Whether we should expect an returned Array (optional) |
transformResponse | Function/Array | Transform returned response (optional) |
import {defaultActions} from 'redux-rest-resource';
defaultActions == {
"create": {
"method": "POST"
},
"fetch": {
"method": "GET",
"isArray": true
},
"get": {
"method": "GET"
},
"update": {
"method": "PATCH"
},
"delete": {
"method": "DELETE"
}
}
import {defaultHeaders} from 'redux-rest-resource';
defaultHeaders == {
"Accept": "application/json",
"Content-Type": "application/json"
}
- You can add/override headers for a single action
import {createResource} from 'redux-rest-resource';
const hostUrl = 'https://api.mlab.com:443/api/1/databases/sandbox/collections';
const jwt = 'xvDjirE9MCIi800xMxi4EKeTm8e9FUBR';
export const {types, actions, reducers} = createResource({
name: 'user',
url: `${hostUrl}/users/:id?apiKey=${apiKey}`,
headers: {
fetch: {
headers: {
Authorization: `Bearer ${jwt}`
}
}
}
});
- Or globally for all actions
import {defaultHeaders} from 'redux-rest-resource';
const jwt = 'xvDjirE9MCIi800xMxi4EKeTm8e9FUBR';
Object.assign(defaultHeaders, {Authorization: `Bearer ${jwt}`});
- You can combine multiple resources (ie. for handling children stores):
import {createResource, mergeReducers} from 'redux-rest-resource';
const hostUrl = 'http://localhost:3000';
const libraryResource = createResource({
name: 'library',
pluralName: 'libraries',
url: `${hostUrl}/libraries/:id`
});
const libraryAssetResource = createResource({
name: 'libraryAsset',
url: `${hostUrl}/libraries/:libraryId/assets/:id`
});
const types = {...libraryResource.types, ...libraryAssetResource.types};
const actions = {...libraryResource.actions, ...libraryAssetResource.actions};
const reducers = mergeReducers(libraryResource.reducers, {assets: libraryAssetResource.reducers});
export {types, actions, reducers};
- Freeze API after beta feedback
- Maybe support different naming strategies (types and actions)
- Allow store layout customization (reducers)
- Support optimistic updates
Script | Description |
---|---|
test | Run mocha unit tests |
lint | Run eslint static tests |
test:watch | Run and watch mocha unit tests |
compile | Compile the library |
Olivier Louvignes
Inspired by the AngularJS resource.
The MIT License
Copyright (c) 2016 Olivier Louvignes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.