Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redux Query Middleware – Automatically add request headers using custom network interface interceptor.

Example Usage

You need to have the following in your initialization file (index.js or redux/index.js):

...
import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
import {entitiesReducer, queriesReducer} from 'redux-query';
import reduxQueryMiddleware from './middleware/reduxQuery';

...

const store = createStore(
  combineReducers({
    ...reducers,
    entities: entitiesReducer,
    queries: queriesReducer
  }),
  getInitialState(),
  composeEnhancers(
    applyMiddleware(
      queryMiddleware(() => store)
    )
  ));

And the reduxQueryMiddleware.js file from this gist.

import {queryMiddlewareAdvanced} from 'redux-query';
import originalNetworkInterface from 'redux-query/dist/commonjs/network-interfaces/superagent';
/**
* Custom Redux Query Network Interface factory.
* @param {function} getStore – redux store provider
*/
function createNetworkInterface(getStore) {
/**
* Custom Redux Query Network Interface extension.
* Attaches default `Accept` header (`application/json`).
* Attaches `Content-Type` header when a json body is provided.
* Attaches `Authorization` header providing an `access_token`
* from the redux store (`state.auth.token`).
*/
return function (url, method, config) {
const headers = {
'Accept': 'application/json',
...(config.headers || {})
};
if (!headers['Content-Type'] && (
method === 'POST' || method === 'PUT'
) && config.body) {
headers['Content-Type'] = 'application/json';
}
headers['X-Requested-With'] = 'XMLHttpRequest';
config.headers = headers;
return originalNetworkInterface(url, method, config);
}
}
/**
* Redux Query Middleware factory.
* @param {function} getStore – redux store accessor
* @return {Middleware}
*/
export default (getStore) => {
return queryMiddlewareAdvanced(createNetworkInterface(getStore))(
state => state.queries,
state => state.entities
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.