I'm using React Router Dom v6. So for my web application, I created a Redux action in userAction called logoutUser, and in view dashboard.jsx, I added a logout button that should navigate me to the home page ('/'). My problem is that clicking on logout does nothing, is my code wrong?
userAction.js:
export const logoutUser = (navigate) => {
return () => {
sessionService.deleteSession();
sessionService.deleteUser();
navigate('/');
}
}
dashboard:
import {useNavigate} from 'react-router-dom'
const Dashboard = ({logoutUser}) => {
const navigate = useNavigate();
return (
<div>
<StyledButton bg={colors.red} to="#" onClick={()=>logoutUser(navigate)}>
Logout
</StyledButton>
</div>
);
logoutUser returns a function instead of executing the tasks you want. You either change it to:
export const logoutUser = (navigate) => {
sessionService.deleteSession();
sessionService.deleteUser();
navigate('/');
}
Or change your onClick part to the code below so you execute the function returned by logoutUser:
onClick={()=>logoutUser(navigate)()}
If logoutUser is meant to be an action, then you need to actually dispatch that action to your redux store. This assumes you have correctly added the thunk (or other similar asynchronous action middleware).
Example:
export const logoutUser = (navigate) => () => {
sessionService.deleteSession();
sessionService.deleteUser();
navigate('/');
};
...
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
const Dashboard = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
return (
<div>
<StyledButton
bg={colors.red}
to="#"
onClick={() => dispatch(logoutUser(navigate))}
>
Logout
</StyledButton>
</div>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With