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..
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
});
};