How to pass ReactJS state into Redux Action Creator

Although there are differing opinions on whether accessing state in action creators is a good idea (for example, Dan Abramov strongly discourages such practice), there are some edge cases (such as checking for cached data or for authentication related situations), which will make passing the Redux state into an action creator quite a useful concept.

It turns out that Redux makes this quite easy, through the getState() function. Quoting the official Redux documentation:

getState() returns the current state tree of your application. It is equal to the last value returned by the store's reducer

So let's say we have a reducer that returns the state of a Redux Form and of the application's authentication such as the following:

For the action creator to access the auth state, all we need to do is use the getState() function. First we need to pass it as the second argument after the dispatch, and then save its return as the application state tree:

To get a specific value instead of the whole tree, since state is an object, I can use the object dot notation, as in the quoted example. Alternatively, you can use the ES6 destructuring notation: const { auth } = getState()

In general I try not to pass any state to the action creator and try to solve my problem in a different way (for example, by dispatching multiple actions). But if there are still no alternatives, at the very minimum, I recommend passing the state at the very end of the application state chain. This is to minimise the risk of application state mutation in the wrong places.

No comments: