Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions lib/hooks/api/beatmap/useBeatmap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,17 @@ import useSWR from "swr";

import type { BeatmapResponse } from "@/lib/types/api";

import { useToastApiRequestFailed } from "../../useToastApiRequestFailed";

export function useBeatmap(beatmapId: number | null) {
return useSWR<BeatmapResponse>(beatmapId ? `beatmap/${beatmapId}` : null, {
dedupingInterval: 1000 * 60 * 10,
});
const swrResult = useSWR<BeatmapResponse>(
beatmapId ? `beatmap/${beatmapId}` : null,
{
dedupingInterval: 1000 * 60 * 10,
},
);

useToastApiRequestFailed(swrResult);

return swrResult;
}
8 changes: 7 additions & 1 deletion lib/hooks/api/beatmap/useBeatmapSet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@ import useSWR from "swr";

import type { BeatmapSetResponse } from "@/lib/types/api";

import { useToastApiRequestFailed } from "../../useToastApiRequestFailed";

export function useBeatmapSet(beatmapSetId: number | null) {
return useSWR<BeatmapSetResponse>(
const swrResult = useSWR<BeatmapSetResponse>(
beatmapSetId ? `beatmapset/${beatmapSetId}` : null,
{
dedupingInterval: 1000 * 60 * 10,
},
);

useToastApiRequestFailed(swrResult);

return swrResult;
}
49 changes: 49 additions & 0 deletions lib/hooks/useToastApiRequestFailed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"use client";

import type { HTTPError } from "ky";
import { useEffect, useRef } from "react";
import type { SWRResponse } from "swr";

import { useToast } from "@/hooks/use-toast";

import type { ProblemDetailsResponseType } from "../types/api";

export function useToastApiRequestFailed<T>(swrResult: SWRResponse<T>) {
const { toast } = useToast();
const lastErrorRef = useRef<Error | null>(null);

useEffect(() => {
const { error } = swrResult;

if (error && error !== lastErrorRef.current) {
lastErrorRef.current = error;

if (error instanceof Error && "response" in error) {
const httpError = error as HTTPError;

if (httpError.response?.status && httpError.response.status >= 404) {
try {
const problemDetails = JSON.parse(httpError.message) as ProblemDetailsResponseType;

if (!problemDetails.detail)
throw new Error("No detail in problem details response");

toast({
title: "Error",
description: problemDetails.detail,
variant: "destructive",
});
}
catch {
// Ignore the error if it's not a ProblemDetailsResponseType
}
}
}
}

if (!error && lastErrorRef.current) {
lastErrorRef.current = null;
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- Only need to react to error changes
}, [swrResult.error, toast]);
}