Easy-peasy: Listen to reducers

Created on 10 Feb 2019  路  5Comments  路  Source: ctrlplusb/easy-peasy

Is there a way to listen to actions added through reducers? Trying to run easy-peasy actions in response to a Router changes via redux-first-history, and listen only applies to those in easy-peasy's format.

I've updated the todo sandbox and changed preferences to a reducer to simulate. Would this have to run through some custom middleware?

Example
https://codesandbox.io/s/zqx558q8jl

// Example reducer
function reducerPreferences(state = { theme: "light" }, action) {
  switch (action.type) {
    case "toggle": {
      return { ...state, theme: state.theme === "light" ? "dark" : "light" };
    }
    default: {
      return state;
    }
  }
}

const log = msg => (...args) => console.log(msg, ...args);

const model = {
  preferences: reducer(reducerPreferences),
  todos: {
    items: {},
    listeners: listen(on => {
      // Works
      on(model.todos.fetched, log("fetched"));

      // How to listen to reducer?
      on(reducer(reducerPreferences), log("reducerPreferences"));
      on(model.preferences, log("preferences"));
      on(model.preferences.toggle, log("toggle"));
      on({ type: "toggle" }, log("actionToggle"));
    }),

All 5 comments

Interesting case! I have a good idea. This will be super helpful for compatibility and migration cases. I will write up an example for you tomorrow. 馃憤

Hey @ifyoumakeit

I have created PR #84 which addresses this. 馃憤

import { listen } from 'easy-peasy';

const model = {
  msg: '',
  set: (state, payload) => { state.msg = payload; },

  listeners: listen((on) => {
    //      馃憞 passing in action name
    on('ROUTE_CHANGED', (actions, payload) => {
      //                            馃憜
      // We won't know the type of payload, so it will be "any".
      // You will have to annotate it manually if you are using 
      // Typescript and care about the payload type.
      actions.set(`Route was changed`);
    });
  })
};

You can test it out via the following published version:

npm install [email protected]

Would you mind trying it out and feeding back to me?

Sounds good @ctrlplusb! Thanks for working on this.

I've merged :)

Thanks! This is working great!

Was this page helpful?
0 / 5 - 0 ratings