perf : cache
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useCommentLocale } from "./comment-locale";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { CommentPage } from "@/lib/comments/types";
|
||||
import { commentRequest } from "./client";
|
||||
|
||||
export function useCommentFeed(endpoint: string, initial?: CommentPage) {
|
||||
const { request: commentRequest, t } = useCommentLocale();
|
||||
const [page, setPage] = useState<CommentPage>(initial ?? { items: [], nextCursor: null, viewer: null });
|
||||
const [dataEndpoint, setDataEndpoint] = useState(endpoint);
|
||||
const [busy, setBusy] = useState(!initial);
|
||||
@@ -38,9 +40,9 @@ export function useCommentFeed(endpoint: string, initial?: CommentPage) {
|
||||
setDataEndpoint(endpoint); setError("");
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted && sequence === generation.current) setError(cause instanceof Error ? cause.message : "ไม่สามารถโหลดความคิดเห็นได้");
|
||||
if (!controller.signal.aborted && sequence === generation.current) setError(cause instanceof Error ? cause.message : t("ไม่สามารถโหลดความคิดเห็นได้", "Could not load comments"));
|
||||
} finally { if (sequence === generation.current) setBusy(false); }
|
||||
}, [endpoint]);
|
||||
}, [endpoint, commentRequest, t]);
|
||||
const more = useCallback(async () => {
|
||||
if (!page.nextCursor || busy) return;
|
||||
const sequence = ++generation.current;
|
||||
@@ -54,9 +56,9 @@ export function useCommentFeed(endpoint: string, initial?: CommentPage) {
|
||||
loadedPages.current += 1;
|
||||
setError("");
|
||||
}
|
||||
} catch (cause) { if (sequence === generation.current) setError(cause instanceof Error ? cause.message : "ไม่สามารถโหลดความคิดเห็นได้"); }
|
||||
} catch (cause) { if (sequence === generation.current) setError(cause instanceof Error ? cause.message : t("ไม่สามารถโหลดความคิดเห็นได้", "Could not load comments")); }
|
||||
finally { if (sequence === generation.current) setBusy(false); }
|
||||
}, [endpoint, page, busy]);
|
||||
}, [endpoint, page, busy, commentRequest, t]);
|
||||
useEffect(() => {
|
||||
if (mountedEndpoint.current !== endpoint) {
|
||||
loadedPages.current = 1;
|
||||
|
||||
Reference in New Issue
Block a user