feat(splash): load latest chat message
Docker Image / Build and Push Docker Image (push) Has been cancelled
Docker Image / Build and Push Docker Image (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import type { LoginStatus } from "@/data/dto/auth";
|
||||
import { fetchSplashLatestMessagePreview } from "@/lib/chat/splash_latest_message";
|
||||
import { Logger, Result } from "@/utils";
|
||||
|
||||
const log = new Logger("SplashLatestMessage");
|
||||
|
||||
export interface UseSplashLatestMessageInput {
|
||||
hasInitialized: boolean;
|
||||
isAuthLoading: boolean;
|
||||
loginStatus: LoginStatus;
|
||||
}
|
||||
|
||||
export interface UseSplashLatestMessageOutput {
|
||||
message: string | null;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
interface SplashLatestMessageState {
|
||||
key: string;
|
||||
loaded: boolean;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
export function useSplashLatestMessage({
|
||||
hasInitialized,
|
||||
isAuthLoading,
|
||||
loginStatus,
|
||||
}: UseSplashLatestMessageInput): UseSplashLatestMessageOutput {
|
||||
const [state, setState] = useState<SplashLatestMessageState>({
|
||||
key: "",
|
||||
loaded: false,
|
||||
message: null,
|
||||
});
|
||||
const shouldLoad =
|
||||
hasInitialized && !isAuthLoading && loginStatus !== "notLoggedIn";
|
||||
const requestKey = shouldLoad ? loginStatus : "";
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldLoad) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const loadLatestMessage = async () => {
|
||||
const result = await fetchSplashLatestMessagePreview();
|
||||
if (cancelled) return;
|
||||
|
||||
if (Result.isErr(result)) {
|
||||
log.warn(
|
||||
{ err: result.error.message },
|
||||
"[splash] latest message history request failed",
|
||||
);
|
||||
setState({ key: requestKey, loaded: true, message: null });
|
||||
return;
|
||||
}
|
||||
|
||||
setState({
|
||||
key: requestKey,
|
||||
loaded: true,
|
||||
message: result.data,
|
||||
});
|
||||
};
|
||||
|
||||
void loadLatestMessage();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [requestKey, shouldLoad]);
|
||||
|
||||
if (!shouldLoad) return { message: null, isLoading: false };
|
||||
if (state.key !== requestKey || !state.loaded) {
|
||||
return { message: null, isLoading: true };
|
||||
}
|
||||
return { message: state.message, isLoading: false };
|
||||
}
|
||||
Reference in New Issue
Block a user