Waiting for the action to complete in React Redux

I will try to explain briefly how data flow works in a Redux application:

  1. The reducer should not be called directly from the component. Your call to authenticate user should be inside an action and that is what should be dispatched from the component.

  2. When you define the action, you can give a property to define the type of action it is. For example, in this case, it could be type: AUTHENTICATE_USER

  3. After the completion of the action, the redux store calls the reducer where with the current state and the action. Here, the redux state can be updated based on action.type (the second code snippet above)

  4. This is the most important part: your component needs to have a mapStateToProps method which passes values from your Redux state as props into your component. So as the state changes, the props get updated and the component re-renders. To use mapStateToProps, you need to implement connect from the react-redux library. (https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options)

To achieve what you want, this is what I suggest:

  1. In your component's componentWillReceiveProps method, checking for props.isAuthenticated and using context.router.push() to navigate if the user is authenticated.

  2. Also having a check based on props.isAuthenticated in the component's render method to show the error message.

A few links which could be useful:

https://redux.js.org/basics/data-flow

https://redux.js.org/basics/usage-with-react


I prefer code like this:

const mapStateToProps = (state) => {
  return {
      isAuthenticated: state.isAuthenticated
  }
}

class Dashboard extends PureComponent {
  render() {
    const { isAuthenticated } = this.props

    return (
      <div>
        { isAuthenticated ? (
          <div>
            <p>Hello</p>
          </div>
        ) : (
          Login()
        )}
      </div>
    )
  }
}

Source: https://stackoverflow.com/a/56899814/3850405

Addition to the answer from @Nupur. componentWillReceiveProps() is considered unsafe and the method name now is: UNSAFE_componentWillReceiveProps()

https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

Use componentDidUpdate() instead if you would like this approach, this method is not called for the initial render.

componentDidUpdate(prevProps) {
    if (this.props.isAuthenticated ) {
        //perform code here
    }
}

https://reactjs.org/docs/react-component.html#componentdidupdate