Question:
I’m building a web application Reactjs and Redux, where you can login to dashboard and then you can logout. I’m using “redux-react-session” to manage sessions, and i created an action called logoutUser in userActions.js. this action is imported and called in Dashboard.jsx where i added a logout button with onClick event. What i’m expecting is when i click on logout it should simply redirects me to home page (‘/’)My problem is: Whenever i click on logout button, it redirects me to home page (‘/’) then refreshing back to dashboard.
Console.dev error:
Uncaught Error: Actions must be plain objects. Instead, the actual type was: ‘undefined’. You may need to add middleware to your store setup to handle dispatching other values, such as ‘redux-thunk’ to handle dispatching functions.
userAction.js:
If i add
return()
in the action:Removing
return ( ) => {
… }
and ( )
of logoutUser(navigate)( )
will keep the page refreshing then get me back to dashboardAnswer:
It seems the issue is related to using both theconnect
Higher Order Component and manually dispatching actions to the store. The connect
HOC automatically wraps the action creators in a call to dispatch
and injects a dispatchable action as a prop into the decorated component. Your code is then wrapping logoutUser
in another call to dispatch
. Pick one or the other, but not both.Using connect
HOC
Using useDispatch
hook
You may need to add middleware to your store setup to handle dispatching other values, such as ‘redux-thunk’ to handle dispatching functions.
I suggest following the
redux
and react-redux
guides for adding this to your store configuration, or update to redux-toolkit
(same maintainers) which includes the thunk middleware out-of-the-box since it is such a common use case.If you have better answer, please add a comment about this, thank you!