You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tailchat/client/shared/cache/useCache.ts

57 lines
1.1 KiB
TypeScript

import { useQuery } from 'react-query';
import {
fetchUserInfo,
getUserOnlineStatus,
UserBaseInfo,
} from '../model/user';
import { isValidStr } from '../utils/string-helper';
/**
*
*/
export function useCachedUserInfo(
userId: string | null,
refetch = false
): UserBaseInfo | Record<string, never> {
const { data } = useQuery(
['user', userId],
() => {
if (!isValidStr(userId)) {
return {};
}
return fetchUserInfo(userId);
},
{
staleTime: 2 * 60 * 60 * 1000, // 缓存2小时
refetchOnMount: refetch ? 'always' : true,
}
);
return data ?? {};
}
/**
*
*/
export function useCachedOnlineStatus(
ids: string[],
onOnlineStatusUpdate?: (onlineStatus: boolean[]) => void
): boolean[] {
const { data, isSuccess } = useQuery(
['onlineStatus', ids.join(',')],
() => getUserOnlineStatus(ids),
{
staleTime: 10 * 1000, // 缓存10s
}
);
if (isSuccess && Array.isArray(data)) {
if (typeof onOnlineStatusUpdate === 'function' && data) {
onOnlineStatusUpdate(data);
}
}
return data ?? ids.map(() => false);
}