Waiting for the action to complete in React Redux
I will try to explain briefly how data flow works in a Redux application:
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.
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
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)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 usemapStateToProps
, 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:
In your component's
componentWillReceiveProps
method, checking forprops.isAuthenticated
and usingcontext.router.push()
to navigate if the user is authenticated.Also having a check based on
props.isAuthenticated
in the component'srender
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