nathanbuchar / react-hook-thunk-reducer

📡 A React useReducer() hook whose dispatcher supports thunks à la redux-thunk.
MIT License
108 stars 14 forks source link

Support middleware? #10

Closed zaydek-old closed 5 years ago

zaydek-old commented 5 years ago

Hi Nathan, forgive me if I don’t understand the API perfectly, but as I understand it, the current implementation does not support adding custom middleware functions?

I think it would really add to the usefulness of this package. What do you think?

nathanbuchar commented 5 years ago

I don't disagree about extending this module. For its first release, I just wanted it to be an exact replica of useReducer, but with thunk support.

I'm not certain I understand how middleware might be useful. Can you give me an example of how you're picturing you might use middleware with this module?

zaydek-old commented 5 years ago

Hey Nathan, I agree with your approach.

The use case I have in mind is for enabling logging per action, enabled via a debug flag. But if you or people don’t have that need, no worries.

sirugh commented 5 years ago

@ZAYDEK Not sure that middleware would apply here. You could write your own reducer wrapper that decorates the function. We do something like this:

const withLogger = reducer => (state, action) => {
    const result = reducer(state, action);

    console.groupCollapsed(action.type);
    console.group('payload');
    console.log(action.payload);
    console.groupEnd();
    console.group('next state');
    console.log(result);
    console.groupEnd();
    console.groupEnd();

    return result;
};

const wrappedReducer = withLogger(reducer);
function Counter () {
  const [state, dispatch] = useThunkReducer(wrappedReducer, initialState);
  ...
}
zaydek-old commented 5 years ago

That’s great, much appreciated. Feel free to close this issue. :)

nathanbuchar commented 5 years ago

@sirugh Thanks for the suggestion :)