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>
);
CodePudding user response:
logoutUser
is returning a function instead of executing the tasks you want. You either change it to:
export const logoutUser = (navigate) => {
sessionService.deleteSession();
sessionService.deleteUser();
navigate('/');
}
Or your change your onClick
part, to the code below, so you execute the function retuned by logoutUser
:
onClick={()=>logoutUser(navigate)()}
CodePudding user response:
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>
);
};