likerRr
likerRr

Reputation: 1296

Dispatching several actions in sequence for single reducer doesn't reflect changes in state for connected component

When dispatching several different actions for one reducer, only the last one triggers component update. It might be better to show then explain.

Some notes on provided example:

  1. App component reflects a history of updates of it's prop redirectPath. When it comes as null then no redirect string adds to history.
  2. There is a reducer which returns just a plain string or null depending on action.
  3. By pressing a button Do redirect I expect both actions (SET_REDIRECT and CLEAR_REDIRECT) provide changed state to AppContainer component. But only the latest one (CLEAR_REDIRECT) triggers render method with null value.
  4. If we add slight delay between dispatching these actions, then both of them trigger component's render. You can check it by pressing Do redirect with delay button.

I expect both changes (provided by SET_REDIRECT and CLEAR_REDIRECT actions) in state should trigger component update without using setTimeout when dispatching actions.

I also tried to move dispatching of CLEAR_REDIRECT from middleware, after it gets SET_REDIRECT, but the same result.

Can I somehow reach expected behaviour?

Initially I posted the issues to redux repo, because I thought it's an issue in redux, but @jimbolla explained me that it's mostly by design of react.

Here is the reference to the original issues and comments from redux team member https://github.com/reactjs/redux/issues/2532.

Upvotes: 0

Views: 216

Answers (1)

Martin Campbell
Martin Campbell

Reputation: 1798

Don't ever rely on performing state updates in render(). The only code that should be executed in render() is the code required to construct the view.

You could use componentWillReceiveProps to track when your component receives new properties.

You should listen for the appropriate property and perform your redirect when received. You should then listened for a property that indicates the redirection was successful and then you can dispatch an action to clear the redirect state if required which will trigger another component update.

Upvotes: 1

Related Questions