I was trying to create a middleware which takes care of all my APIS.
Store Configuration
In my store I am adding apiMiddleware to use [CALL_API]
. Along with this I am adding redux-thunk using extraArgument to access the generic API I create in my dispatch method.
export default function configureStore(initialState) {
const store=createStore(
rootReducer,
initialState,
compose(
applyMiddleware(apiMiddleware,thunk.withExtraArgument(api))))
return store
}
Reducer
const initialState = {
data : []
}
export default function users(state=initialState,action){
switch(action.type){
case 'RECEIVE_USER_DATA':
return Object.assign({},state,{
data : action.payload
})
case 'FAILURE_USER_DATA':
return state
default:
return state;
}
}
Action
export function fetchUserData(){
return (dispatch,getState,api) => {
const url = 'https://jsonplaceholder.typicode.com/users/';
const method = 'GET'
const actionTypes = ['REQUEST_USER_DATA','RECEIVE_USER_DATA','FAILURE_USER_DATA']
api(url,method,actionTypes)
}
}
Middleware API
export default function api(url,method,actions){
return {
[CALL_API] : {
endpoint : url,
method : method,
types: actions
}
}
}
This is not working. However if I put the middleware code under my action function it works fine.