Files
kiss-translator/src/hooks/Setting.js

50 lines
1.1 KiB
JavaScript
Raw Normal View History

2023-08-30 18:05:37 +08:00
import { STOKEY_SETTING, DEFAULT_SETTING } from "../config";
import { useStorage } from "./Storage";
2023-07-31 15:08:51 +08:00
import { useSync } from "./Sync";
2023-08-26 14:31:13 +08:00
import { trySyncSetting } from "../libs/sync";
2023-08-30 18:05:37 +08:00
import { createContext, useCallback, useContext } from "react";
2023-07-20 13:45:41 +08:00
2023-08-30 18:05:37 +08:00
const SettingContext = createContext({
setting: null,
updateSetting: async () => {},
2023-09-01 10:15:57 +08:00
reloadSetting: async () => {},
2023-08-30 18:05:37 +08:00
});
export function SettingProvider({ children }) {
2023-09-01 10:15:57 +08:00
const { data, update, reload } = useStorage(STOKEY_SETTING, DEFAULT_SETTING);
2023-08-30 18:05:37 +08:00
const {
sync: { settingUpdateAt },
updateSync,
} = useSync();
const updateSetting = useCallback(
async (obj) => {
const updateAt = settingUpdateAt ? Date.now() : 0;
await update(obj);
await updateSync({ settingUpdateAt: updateAt });
trySyncSetting();
},
2023-08-31 00:18:57 +08:00
[settingUpdateAt, update, updateSync]
2023-08-30 18:05:37 +08:00
);
return (
<SettingContext.Provider
value={{
setting: data,
updateSetting,
2023-09-01 10:15:57 +08:00
reloadSetting: reload,
2023-08-30 18:05:37 +08:00
}}
>
{children}
</SettingContext.Provider>
);
2023-07-20 13:45:41 +08:00
}
/**
2023-08-30 18:05:37 +08:00
* 设置 hook
2023-07-20 13:45:41 +08:00
* @returns
*/
2023-08-30 18:05:37 +08:00
export function useSetting() {
return useContext(SettingContext);
2023-07-20 13:45:41 +08:00
}