0

In redux-api-middleware we can create a API call like below,

export function loadUsers() {
  return {
    [CALL_API]: {
      headers: { 'Content-Type': 'application/json' },
      endpoint: 'http://localhost:1337/users',
      method: 'GET',
      types: [LOAD_USERS_REQUEST, LOAD_USERS_SUCCESS, LOAD_USERS_FAILURE]
    }
  }
}

Problem is, for every request, am using the common end point http://localhost:1337 , Header content type and authorization token settings.

I need a place to set those settings globally, from their official documentation am unable to find the solution. Anybody know this? or have any idea to achieve this ?

Thanks in advance..

Raj Adroit
  • 3,828
  • 5
  • 31
  • 44

1 Answers1

1

In middleware you can get the access to the store state, so you can put token and other auth information into the store and then use it in middleware.

I had the same issue and had ended with implementation like this:

const callApiMiddleware = store => next => action => {
  // skip everything which is not API call
  const callAPI = action[CALL_API]
  if (typeof callAPI === 'undefined') {
    return next(action);
  }

  // the session info from store
  const session = store.getState().session;

  // perform request
  const {endpoint, headers, method} = callAPI;
  return fetch(endpoint, {
    headers: Object.assign({
        Authorization: `Bearer ${session && session.token}`
        // you can add more default headers there if you would like so
    }, headers),
    method
  });
};
just-boris
  • 9,468
  • 5
  • 48
  • 84
  • I got it, this is an our custom middleware, we should add this store by ```applyMiddleware``` method? right? – Raj Adroit Sep 22 '16 at 09:53
  • Yes, this is custom middleware. You can find something similar in redux examples: https://github.com/reactjs/redux/blob/master/examples/real-world/src/middleware/api.js – just-boris Sep 23 '16 at 07:58
  • Nice! @just-boris. What if you need dynamic headers besides the Authorization jwt one? Meaning that one can't know in advance what the headers will be so you can't set them in a custom middleware. Is there anyway to merge dynamic ones with pre-defined ? – tommyalvarez Apr 13 '18 at 13:48