mirror of https://github.com/msgbyte/tailchat
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.
57 lines
1.1 KiB
TypeScript
57 lines
1.1 KiB
TypeScript
4 years ago
|
import { useQuery } from 'react-query';
|
||
4 years ago
|
import {
|
||
|
fetchUserInfo,
|
||
|
getUserOnlineStatus,
|
||
|
UserBaseInfo,
|
||
|
} from '../model/user';
|
||
4 years ago
|
import { isValidStr } from '../utils/string-helper';
|
||
4 years ago
|
|
||
4 years ago
|
/**
|
||
|
* 用户缓存
|
||
|
*/
|
||
|
export function useCachedUserInfo(
|
||
4 years ago
|
userId: string | null,
|
||
4 years ago
|
refetch = false
|
||
|
): UserBaseInfo | Record<string, never> {
|
||
4 years ago
|
const { data } = useQuery(
|
||
|
['user', userId],
|
||
|
() => {
|
||
|
if (!isValidStr(userId)) {
|
||
|
return {};
|
||
|
}
|
||
|
|
||
|
return fetchUserInfo(userId);
|
||
|
},
|
||
|
{
|
||
|
staleTime: 2 * 60 * 60 * 1000, // 缓存2小时
|
||
|
refetchOnMount: refetch ? 'always' : true,
|
||
|
}
|
||
|
);
|
||
4 years ago
|
|
||
|
return data ?? {};
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
/**
|
||
|
* 用户登录状态
|
||
|
*/
|
||
3 years ago
|
export function useCachedOnlineStatus(
|
||
|
ids: string[],
|
||
|
onOnlineStatusUpdate?: (onlineStatus: boolean[]) => void
|
||
|
): boolean[] {
|
||
|
const { data, isSuccess } = useQuery(
|
||
4 years ago
|
['onlineStatus', ids.join(',')],
|
||
|
() => getUserOnlineStatus(ids),
|
||
|
{
|
||
|
staleTime: 10 * 1000, // 缓存10s
|
||
|
}
|
||
|
);
|
||
|
|
||
3 years ago
|
if (isSuccess && Array.isArray(data)) {
|
||
|
if (typeof onOnlineStatusUpdate === 'function' && data) {
|
||
|
onOnlineStatusUpdate(data);
|
||
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
return data ?? ids.map(() => false);
|
||
|
}
|