Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yes, you _can_ actually do that with the listener middleware! We specifically designed that to be possible.

When you add a listener entry, there are four options to specify how the middleware knows when to run that listener: 1) `type`: an action type string; 2) `actionCreator`: an RTK action creator function like `todoAdded`; 3) `matcher`: an `(action: AnyAction): action is MyAction => boolean` type guard; and 4) `predicate`: an `(action, currState, prevState) => boolean` function.

In all cases, the middleware loops over all entries every time an action is dispatched, and checks to see if any entry is interested based on those comparisons. For the first three, it's just "does this action type match".

_But_ the `predicate` callback receives `currState` and `prevState` as arguments. That means that you can write checks to see if "this state field has changed due to the action":

    return currState.counter.value !== prevState.counter.value
or if "this state field matches some condition, such as:

    return currState.counter.value >= 3
This is covered in the API docs:

https://redux-toolkit.js.org/api/createListenerMiddleware#st...

FWIW, skimming the repo you linked (which I assume is your package), I'm pretty sure RTK either does the same things already (creating actions and reducers) or has equivalent solutions (listeners for "selector effects", `createAsyncThunk` for the "async middleware", RTK Query for data fetching).



Yup! I'm aware, it's mostly an exercise I wrote after trying RTK.

It's a combination of two other Redux helpers I've been using for years before RTK existed. All mentioned in the "see also" section.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: