Here is my code to get the dashboard form backend using useEffect and then the handler to handle the logout button
useEffect(() => {
if (!token) {
navigate('/login', { replace: true });
return;
}
const fetchUserData = async () => {
try {
const response = await axios.get('http://localhost:3001/api/auth/dashboard', {
headers: {
Authorization: `Bearer ${token}`,
},
});
setUser(response.data);
} catch (error) {
if (error.response?.status === 401) {
toast.error('Please login to access the dashboard');
navigate('/login', { replace: true });
} else {
toast.error('Failed to fetch user data');
}
} finally {
setIsLoading(false);
}
};
fetchUserData();
}, [navigate, token]);
const handleLogout = () => {
localStorage.removeItem('token');
setUser(null);
toast.success('Logged out successfully!');
navigate('/login', { replace: true });
};
After click on logout button –
- user should redirect to login page but it lstuck on dashboard with a Loading…
user should not stuck on dashboard with loading… screen, user should be redirect to login
if you want to check full code here is the github repo link – https://github.com/SamratPandey/ByteRunners.git
fell free to any suggestions
New contributor
Emperor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3