1.0.9 • Published 5 years ago
redux-fast-axios v1.0.9
redux-fast-axios
Simple redux middleware to make easy axios requests with redux flow
Description
Clean and easy way to make fast axios request
Installation
npm -i --save redux-axios
yarn add redux-axios
Usage
//store.js
import { createStore, applyMiddleware } from 'redux'
import createReduxFastAxiosMiddleware from "redux-fast-axios"
import rootReducer from './rootReducer'
const reduxAxiosMiddleware = createReduxFastAxiosMiddleware(
{
timeout:1000,
defaultHeaders:[{type:'Content-Type',value:'application/json'},{type:'x-access-token',value:localStorage.getItem('token')}],
baseUrl:process.env.NODE_ENV === `development` ? 'http://localhost/api' : 'http://some_prod_url/',
digestAxiosResponse:(response,onSuccess,onFailure)=>{
if(response.data.success){
onSuccess(response.data.success.data)
}
else{
onFailure(response.data.error.message)
}
}
}
)
const store = createStore(
rootReducer,
applyMiddleware(reduxAxiosMiddleware)
)
//actions.js :
import {reduxFastAxiosAction} from "redux-fast-axios"
const doReduxAction = ()=>(dispatch,getState)=>{
dispatch(reduxFastAxiosAction({
url:'some-url', // will be http://localhost/api/some-url //
method:'POSt',
data:{user:''},
type:"SOME_START_TYPE",
onSuccess:(data)=>{
//do something with the callback from digestAxiosResponse
dispatch({type:'SOME_SUCCESS_TYPE',payload:{data}})
},
onFailure:(failureMessage)=>{
//do something with the callback from digestAxiosResponse
dispatch({type:'SOME_FAILURE_TYPE',payload:{failureMessage}})
}
}))
}
Config for createReduxFastAxiosMiddleware
Prop | Description | Default |
---|---|---|
baseUrl | base url for axios | '' |
timeout | timeout for axios request | 0 |
defaultHeaders | default headers array shape of {type,value} for axios | [] |
digestAxiosResponse | custom function to digest the axios response to decide what to return to onSuccess or onFailure callbacks | function |
Future Updates
support more axios configuration