- Notifications
You must be signed in to change notification settings - Fork0
A set of action creators that make it easier to work with axios and redux.
License
benmoose/axios-action-creators
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Axios Action Creators makes it really easy to deal with API responses.Simply define the action creators and then call them when you receive the response to getstandardised actions.
Using npm
npm install axios-action-creators...or using yarn
yarn add axios-action-creatorsimportaxiosfrom'axios'import{REQUEST,SUCCESS,FAILURE}from'axios-action-creators'// (1) Define action typesexportconstGET_USERS_REQUEST='GET_USERS_REQUEST'exportconstGET_USERS_SUCCESS='GET_USERS_SUCCESS'exportconstGET_USERS_FAILURE='GET_USERS_FAILURE'// (2) Define action creators – just pass in the typeconstgetUsersRequest=REQUEST(GET_USERS_REQUEST)constgetUsersSuccess=SUCCESS(GET_USERS_SUCCESS)constgetUsersFailure=FAILURE(GET_USERS_FAILURE)// (3) Call the action creators to get the actionsexportconstgetUsers=()=>(dispatch)=>{// Resolves to a action with type GET_USERS_REQUESTdispatch(getUsersRequest())returnaxios.get('/users')// If successful dispatch GET_USERS_SUCCESS action.then(res=>dispatch(getUsersSuccess(res)))// If failure dispatch GET_USERS_FAILURE action.catch(err=>dispatch(getUsersFailure(err)))}
All action creators optionally take an object which can be used to modify the action.
Valid keys in this object are:
metaadd arbitrary data to ametaproperty in the action.schema(only SUCCESS / FAILURE) anormalizr schema to normalise the response.
import{schema}from'normalizr'constgetGistsRequest=SUCCESS('GET_GISTS_REQUEST')constgetGistsSuccess=SUCCESS('GET_GISTS_SUCCESS')exportconstgetGists=()=>dispatch=>{dispatch(getGistsRequest({meta:{requestedAt:Date.now()}}))axios.get('/username/gists').then(res=>dispatch(getGistsSuccess(res,{meta:{responseAt:Date.now()},schema:newschema.Array('gists')})))}
The dispatched actions would look something like this
// getGistsRequest{type:GET_GISTS_REQUEST,meta:{requestedAt:1513176647405}}// getGistsSuccess{type:GET_GISTS_SUCCESS,payload:{entities:{...},result:[15564,27377, ...]},meta:{responseAt:1513176648004,response:{...}},}
The original unmodified response, if available, is always stored inmeta.response.Request data, either raw or normalised, is always stored inpayload.
About
A set of action creators that make it easier to work with axios and redux.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.