pbojinov
8/22/2016 - 1:51 PM

fetchMiddleware.js

const fetch = (url, params) => ({
  type: 'FETCH',
  url,
  params,
});

const fetchMiddleware = fetchImplementation => store => next => action => {
  if (action.type === 'FETCH') {
    const { url, params } = action;
    const token = store.getState().token;
    _.set(params, 'headers.token', token);
    return fetchImplementation(url, params);
  } else {
    return next(action);
  }
};

const middleware = applyMiddleware(fetchMiddleware(window.fetch));
const store = createStore(reducers, middleware);

// Example action
const getUser = id => async ({ dispatch }) => {
  const result = await dispatch(fetch(`http://api.website.com/${id}`, { method: 'GET' }));
  ...
};