tshaddix / webext-redux

A set of utilities for building Redux applications in Web Extensions.
MIT License
1.22k stars 180 forks source link

alias middleware: questions and suggestion #250

Closed wachunei closed 4 years ago

wachunei commented 4 years ago

I'm taking a look at the alias middleware source code:

export default (aliases) => () => (next) => (action) => {
  const alias = aliases[action.type];

  if (alias) {
    return next(alias(action));
  }

  return next(action);
};

and I have a question: why do we push down the middleware chain the return of the alias? This would mean every alias must resolve to an action.

Is this intended?

My approach

Heavily inspired by redux-thunk (which is kinda the same idea) I came up with this alias middleware:

const customAliasMiddleware = (aliases) => ({ dispatch, getState }) => (next) => (action) => {
  const alias = aliases[action.type];
  if (alias) {
    return alias(action, { dispatch, getState });
  }

  return next(action);
};

Main differences are:

tshaddix commented 4 years ago

Hi @wachunei! These are great questions.

Yes, this is intended behavior for the alias middleware. The only thing we wanted aliases to be used for is "swapping" one action for another, and allowing other middleware down the chain to respond to this new action.

To your point, most people that I've worked with have used aliases with redux thunk, so there is not as large a need to pass it to additional middleware. That said, there are members who use aliases in a long chain of custom middleware, and we've designed the current middleware to support both use cases.

wachunei commented 4 years ago

Hi @tshaddix!

I see! Here I'm actually manually composing alias and a redux-thunk equivalent.

I should decouple them and compose them as middlewares, and wherever I was using my custom middleware thunks (action, { dispatch, getState } ) => {} turn it into a regular thunk (action) => (dispatch, getState) => {} and let the middlewares handle them.

Thank you for your answer! Going to close this.

tshaddix commented 4 years ago

@wachunei No problem! Exactly.

That said, it really is up to however you want to do it - that's why we built the aliases as a middleware you can include or not include. The custom middleware you made makes a lot of sense for the problem you are trying to solve!