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.
56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
3 years ago
|
import { useQuery, useQueryClient } from 'react-query';
|
||
|
import {
|
||
|
getUserSettings,
|
||
|
setUserSettings,
|
||
|
UserSettings,
|
||
|
} from '../../model/user';
|
||
|
import { useAsyncRequest } from '../useAsyncRequest';
|
||
|
|
||
|
/**
|
||
|
* 用户设置hooks
|
||
|
*/
|
||
|
export function useUserSettings() {
|
||
|
const client = useQueryClient();
|
||
|
const { data: settings, isLoading } = useQuery(
|
||
|
['useUserSettings'],
|
||
|
() => getUserSettings(),
|
||
|
{
|
||
|
staleTime: 1 * 60 * 1000, // 缓存1分钟
|
||
|
}
|
||
|
);
|
||
|
|
||
|
const [{ loading: saveLoading }, setSettings] = useAsyncRequest(
|
||
|
async (settings: UserSettings) => {
|
||
|
const newSettings = await setUserSettings(settings);
|
||
|
|
||
|
client.setQueryData(['useUserSettings'], () => newSettings);
|
||
|
},
|
||
|
[client]
|
||
|
);
|
||
|
|
||
|
return {
|
||
|
settings: settings ?? {},
|
||
|
setSettings,
|
||
|
loading: isLoading || saveLoading,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 单个用户设置
|
||
|
*/
|
||
3 years ago
|
export function useSingleUserSetting<K extends keyof UserSettings>(
|
||
|
name: K,
|
||
|
defaultValue?: UserSettings[K]
|
||
3 years ago
|
) {
|
||
|
const { settings, setSettings, loading } = useUserSettings();
|
||
|
|
||
|
return {
|
||
|
value: settings[name] ?? defaultValue,
|
||
3 years ago
|
setValue: async (newVal: UserSettings[K]) =>
|
||
3 years ago
|
setSettings({
|
||
|
[name]: newVal,
|
||
|
}),
|
||
|
loading,
|
||
|
};
|
||
|
}
|