0

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.

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.