The logout function is used to log out a user by making an API call and deleting this user's information from LocalStorage and from the Redux store. This function therefore uses two hooks: useDispatch and useFetch (custom hook)
import {useDispatch} from 'react-redux'
import {disconnectUser} from 'store/authentication/authentication.slice'
import useFetch from 'api/useFetch'
import {routes} from 'routes/url'
type ResponseAPI = Record<string, never>
function logout(): void {
const dispatch = useDispatch()
const {call: disconnect} = useFetch<ResponseAPI>('auth/logout', {
fetchOnLoad: false,
method: 'POST',
})
disconnect()
?.then(() => {
dispatch(disconnectUser())
localStorage.removeItem('authenticated')
localStorage.removeItem('decodedId')
localStorage.removeItem('token')
localStorage.removeItem('username')
location.replace(routes.login)
})
.catch(error => Promise.reject(error))
return
}
export default logout
I want to use this logout function in a button, as soon as the user clicks on the Logout button, it will be logged out.
const LogoutButton = (): JSX.Element => {
return (
<div className={styles.container}>
<Button action={() => logout()}>Logout</Button>
</div>
)
}
export default LogoutButton
Unfortunately I get this error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Do you have any ideas ? A big thank-you
logout is not a function it's the hook, and you can't use hook inside the function, because when you do action={() => logout()} you are wrapping hook inside the function. Which is not valid in the function component.
<Button action={logout}>Logout</Button>
Another Way
function useLogout() {
const dispatch = useDispatch();
const { call: disconnect } =
useFetch <
ResponseAPI >
("auth/logout",
{
fetchOnLoad: false,
method: "POST",
});
const logout = () => {
disconnect()
?.then(() => {
dispatch(disconnectUser());
localStorage.removeItem("authenticated");
localStorage.removeItem("decodedId");
localStorage.removeItem("token");
localStorage.removeItem("username");
location.replace(routes.login);
})
.catch((error) => Promise.reject(error));
};
return { logout };
}
// Component
const LogoutButton = (): JSX.Element => {
const { logout } = useLogout();
return (
<div className={styles.container}>
<Button action={() => logout()}>Logout</Button>
</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