Skip to content

Commit 63c0ce2

Browse files
Sign out user on 404 during user data fetch
Updates useUserData hook to sign out the user and redirect to the homepage if the user data fetch returns a 404 status. This helps handle cases where the user no longer exists in the system.
1 parent f1300a9 commit 63c0ce2

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

hooks/useUserData.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { getSelectedYearAbsences } from '@utils/getSelectedYearAbsences';
22
import { Role, UserData } from '@utils/types';
3-
import { useSession } from 'next-auth/react';
3+
import { signOut, useSession } from 'next-auth/react';
44
import { useCallback, useEffect, useState } from 'react';
55

66
interface UseUserDataReturn extends UserData {
@@ -28,7 +28,14 @@ export const useUserData = (): UseUserDataReturn & {
2828
const res = await fetch(
2929
`/api/users/${session.user.id}?getAbsences=true`
3030
);
31-
if (!res.ok) throw new Error('Failed to fetch user');
31+
if (!res.ok) {
32+
if (res.status === 404) {
33+
await signOut({ callbackUrl: '/' });
34+
return;
35+
}
36+
37+
throw new Error(`Failed to fetch user: ${res.status}`);
38+
}
3239
const user = await res.json();
3340

3441
const today = new Date();

0 commit comments

Comments
 (0)