Files
the-biergarten-app/archive/next-js-web-app/src/hooks/data-fetching/beer-likes/useCheckIfUserLikesBeerPost.ts
2026-04-20 02:30:25 -04:00

57 lines
1.6 KiB
TypeScript

import UserContext from '@/contexts/UserContext';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { useContext } from 'react';
import useSWR from 'swr';
import { z } from 'zod';
/**
* A custom hook to check if the current user has liked a beer post.
*
* @param beerPostId The ID of the beer post.
* @returns An object with the following properties:
*
* - `error`: The error that occurred while fetching the data.
* - `isLoading`: A boolean indicating whether the data is being fetched.
* - `mutate`: A function to mutate the data.
* - `isLiked`: A boolean indicating whether the current user has liked the beer post.
*/
const useCheckIfUserLikesBeerPost = (beerPostId: string) => {
const { user } = useContext(UserContext);
const { data, error, isLoading, mutate } = useSWR(
`/api/beers/${beerPostId}/like/is-liked`,
async (url) => {
if (!user) {
throw new Error('User is not logged in.');
}
const response = await fetch(url);
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('Invalid API response.');
}
const { payload } = parsed.data;
const parsedPayload = z.object({ isLiked: z.boolean() }).safeParse(payload);
if (!parsedPayload.success) {
throw new Error('Invalid API response.');
}
const { isLiked } = parsedPayload.data;
return isLiked;
},
);
return {
isLiked: data,
error: error as unknown,
isLoading,
mutate,
};
};
export default useCheckIfUserLikesBeerPost;