fix: 房间不存在时展示错误页面,替代无限加载转圈
This commit is contained in:
@@ -4,16 +4,27 @@ import useSWR from "swr";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { RoomStatus } from "@/types";
|
||||
|
||||
const fetcher = (url: string) => fetch(url).then((r) => r.json());
|
||||
async function fetcher(url: string) {
|
||||
const r = await fetch(url);
|
||||
if (!r.ok) {
|
||||
const err = new Error(r.status === 404 ? "NOT_FOUND" : "FETCH_ERROR");
|
||||
throw err;
|
||||
}
|
||||
return r.json();
|
||||
}
|
||||
|
||||
export function useRoomPolling(roomId: string) {
|
||||
const { data, error, isLoading, mutate } = useSWR<RoomStatus>(
|
||||
`/api/room/${roomId}`,
|
||||
fetcher,
|
||||
{ revalidateOnFocus: true },
|
||||
{
|
||||
revalidateOnFocus: true,
|
||||
shouldRetryOnError: (err) => err?.message !== "NOT_FOUND",
|
||||
},
|
||||
);
|
||||
|
||||
const fallbackRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const notFound = error?.message === "NOT_FOUND";
|
||||
|
||||
useEffect(() => {
|
||||
const es = new EventSource(`/api/room/${roomId}/events`);
|
||||
@@ -60,6 +71,7 @@ export function useRoomPolling(roomId: string) {
|
||||
likeCounts: data?.likeCounts ?? {},
|
||||
swipeCounts: data?.swipeCounts ?? {},
|
||||
restaurants: data?.restaurants ?? [],
|
||||
notFound,
|
||||
isLoading,
|
||||
error,
|
||||
mutate,
|
||||
|
||||
Reference in New Issue
Block a user