qkreltms / react-action-listener

Middleware, React hook which allows making side effect and listening actions of Context or Redux
MIT License
8 stars 0 forks source link

feat: support context API #25

Closed qkreltms closed 3 years ago

qkreltms commented 3 years ago

I think we can support context API to listen an action which usinguseReducer by attaching custom middleware.

const initialState = {count: 0};

function reducer(state, action) {
 // add middleware here
 middleware(state, action)
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
qkreltms commented 3 years ago

I think we should change middleware on reducer to before dispatching action. because of Link

  const actions = {
    increase: () => {
      middleware({ type: "INCREASE", payload: 1 });
      return dispatch({ type: "INCREASE", payload: 1 });
    },
    substract: () => {
      middleware({ type: "SUB", payload: 1 });
      return dispatch({ type: "SUB", payload: 1 });
    }
  };

https://codesandbox.io/s/simple-react-context-example-2-forked-elys2?file=/src/index.js:749-1039

qkreltms commented 3 years ago

Fun fact redux is ok to dispatching an another action in action, but Context API is not.(May occurs unexpected behavior)