Harkirat Saluja
Harkirat Saluja

Reputation: 8114

Generic API call using redux-middleware and redux-thunk

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.

Upvotes: 0

Views: 869

Answers (1)

Brian
Brian

Reputation: 1036

You don't need to reinvent the wheel. You could use redux-auto to do this.

Here is you example: store/user/init.js:

// Reducer
export default function (state, payload, stage, result) {

  switch(stage){
    case 'FULFILLED':
    return Object.assign({},state,{ data : result })
      break;
    case 'REJECTED':
      break;
    case 'PENDING':
    default :
      break;
  }
  return user;
}
// Action
export function action (payload){
  return fetch('https://jsonplaceholder.typicode.com/users/',{
      method: 'GET'
    }).then( data => data.json() );
}

Working example

Upvotes: 0

Related Questions