In other words, what if we want to trigger an action creator in ReactJS after the Redux application state has finished all its mutations?
Since ReactJS is based on component re-rendering, this should be an easy task right? Well...not really...Usually this is the best task for UI rendering only...but conditional action triggering is something more advanced. Most experienced developers would suggest to use an aptly lifecycle Component method, such as ComponentDidUpdate(). This works in most cases, and in general, is the most recommend method:
The problem is that these lifecycle methods, and any other methods outside the render() function, such as generic helper methods, do not work well with React Router 4, specifically <Redirect /> *. So for example, in my case, I wanted a customer to pay for a subscription, then when my backend server sends a specially crafted response, this will be updated in my Redux state, and hopefully, trigger this action creator. After that, I want the customer to be redirected to a Dashboard component.
*Although we could not use the <Redirect /> method, we can use another React Router 4 redirect technique which works well with helper methods outside render() functions. This technique will be described in a future post. As a sneak peek, this entails using the this.props.history() technique.
Solution
So if I cannot listen to state changes inside a lifecycle/helper method, what is the alternative? We can always listen to state changes inside the rendered component itself. One trick I like to use is putting a ternary operation or a classic old if condition that triggers when on a state change. Remember, when the state is updated, the component is always re-rendered through React Redux until the condition is matched, and triggering the next action creator. This is the flow I am using:Note that in my particular case, the success or error object is only made available inside the state tree once the axios operation is complete, hence why I am using the !! notation.
Remember that once the action creator is fired, remember to reset the state tree, otherwise you will end up an infinite loop and keep triggering the same action creator :)