Isaac
Isaac

Reputation: 12874

Dispatch extra action on every action using middleware

export default ({ dispatch, getState }) => next => action => {
  return next(action);
};

Correct me if I'm wrong, the above should be the template for creating redux middleware. I'm wondering if it's possible to dispatch an extra action in this middleware? Think of it as a logger function which I'm trying to log all actions that's being dispatched.

Instead of console logging here, I wished to store it into another reducer.

In shorts, the idea is one action flows thru this middleware, 1 original action + 1 logging action both being dispatched

Upvotes: 0

Views: 268

Answers (1)

KT-mongo
KT-mongo

Reputation: 2212

Not sure if I get your question if it's possible to dispatch an extra action in this middleware? but you can dispatch as many actions as you want, something like that:

export const getBooks = ({dispatch}) => next => action => {
  next(action);
  if (action.type === 'GET_BOOKS') {
    dispatch({type:'API_REQUEST', payload:'yourUrl'});
  }
  if (action.type === 'SOMETHING_ELSE') dispatch(anotherAction());
};

Then you could add a another middleware to observe the actions dispatched by this one i.e.

export const api = ({dispatch}) => next => action => {

  if(action.type === 'API_REQUEST') {
    const { url } = action.payload;

    fetch(url).then(response => response.json())
      .then((data) => dispatch({ type: 'onSuccess', payload: data }))
      .catch(error => dispatch({ type: 'onError', payload: error }))
  }
  return next(action)
};

Obviously, at your store, the first one need to preceed the second one, i.e.

const middlewares = [getBooks, api];
const store = createStore(yourReducer,applyMiddleware(...middlewares));

Upvotes: 2

Related Questions