keajs / kea-saga

Saga support for kea
https://kea.js.org/effects/saga
MIT License
7 stars 4 forks source link

saga builder does not allow accessing logic fields #38

Open rschyboll opened 2 years ago

rschyboll commented 2 years ago

Hi, it's me, again :D

Another thing i noticed when using the kea-saga plugin, the saga builder, which allows starting the saga after mounting the logic, does not accept as input a callback, to allow access logic parameters, like props for example.

I do see why this is the case, as it is impossible to differentiate a saga between a callback which accepts a logic, as both are functions in js.

A proposal that i would have, in my own project I've written such a builder:

export function startSagas<L extends Logic = Logic>(
  input: (logic: L) => Saga[] | Saga,
): LogicBuilder<L> {
  return (_logic) => {
    const logic = _logic as Logic as LogicWithSaga;
    addGetAndFetch(logic);

    const sagas = input(_logic);

    if (Array.isArray(sagas)) {
      for (const localsaga of sagas) {
        saga(localsaga)(_logic);
      }
    } else {
      saga(sagas)(_logic);
    }
  };

It's just a builder that allows launching one or multiple sagas after logic mounted, with access to all logic fields. Maybe adding such a builder to the plugin would be helpful for other people, if you want I could make a pull request with it.

mariusandra commented 2 years ago

Hey, in a saga you can normally use this to access the logic itself. E.g. this.actions.doBla(). We use function.bind(logic) in many places in the builder.

Would that work for you as well?

rschyboll commented 2 years ago

Hey, it does only partially solve my issue, as I'm writing with typescript, and using this, does not provide any type annotations :( Is there maybe some other solution to this?

mariusandra commented 2 years ago

Hmm... one other option is to just use the logic itself:

const someLogic = kea([
  saga(() => {
    console.log(someLogic.values.bla)
    const { doSomething } = someLogic(this.props)
  })
])

However, I noticed that all the sagas just get zero arguments, so I think there's really no reason to just not pass on the logic as the first argument. So 3.1.0 does that.

It'll be a breaking change to whoever is reusing a saga/worker with a default first argument directly in a logic, but I think it's an acceptable risk.