mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 18:52:06 +00:00
Implement login, add useUser hook
This commit is contained in:
35
hooks/useUser.ts
Normal file
35
hooks/useUser.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import GetUserSchema from '@/services/user/schema/GetUserSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import useSWR from 'swr';
|
||||
|
||||
const useUser = () => {
|
||||
const {
|
||||
data: user,
|
||||
error,
|
||||
isLoading,
|
||||
} = useSWR('/api/users/current', async (url) => {
|
||||
const response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.error.message);
|
||||
}
|
||||
|
||||
const parsedPayload = GetUserSchema.safeParse(parsed.data.payload);
|
||||
if (!parsedPayload.success) {
|
||||
throw new Error(parsedPayload.error.message);
|
||||
}
|
||||
|
||||
return parsedPayload.data;
|
||||
});
|
||||
|
||||
return { user, isLoading, error: error as unknown };
|
||||
};
|
||||
|
||||
export default useUser;
|
||||
Reference in New Issue
Block a user