Reselect: Reuse selectors for getState in thunks?

Created on 10 Oct 2017  路  3Comments  路  Source: reduxjs/reselect

Probably a bad idea but I am not afraid to ask silly questions here :)

So yeah you know there is the getState parameter for redux thunks like that

function doSomething () {
  return (dispatch, getState) => {
    ...
  }
}

Often I end up using const flag = getState().get('something').get('flag'), this to compute a piece of state. And I already have that code implemented in a selector using reselect.

I understand it's an anti-pattern to use reselect in redux actions, although I end up writing similar, almost duplicate code here.

Is there a trick, a workaround for that?

Most helpful comment

It's _not_ an anti-pattern to use selectors inside of thunks. In fact, it's a _good_ idea to use selectors anywhere you need to extract specific pieces of data from the Redux state. That includes mapState functions, thunks, sagas, and even inside reducers.

I wrote an article that discusses the pros and cons of accessing state in thunks overall, which I'd recommend reading: Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability.

All 3 comments

It's _not_ an anti-pattern to use selectors inside of thunks. In fact, it's a _good_ idea to use selectors anywhere you need to extract specific pieces of data from the Redux state. That includes mapState functions, thunks, sagas, and even inside reducers.

I wrote an article that discusses the pros and cons of accessing state in thunks overall, which I'd recommend reading: Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability.

thanks heaps for the link! tell me, is there a better place to exchange that stuff rather than here?

also, if you peek over at re-frame, they have coeffects which is what i am after:
https://github.com/Day8/re-frame/blob/master/docs/Coeffects.md

in short, they extract data from the app state we need for event handling.

one important principle is:
"Event handlers should only source data from their arguments"

Was this page helpful?
0 / 5 - 0 ratings