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

80 lines
1.6 KiB
JavaScript
Raw Normal View History

import { useCallback, useMemo } from "react";
2023-08-30 18:05:37 +08:00
import { STOKEY_SYNC, DEFAULT_SYNC } from "../config";
import { useStorage } from "./Storage";
2023-07-31 15:08:51 +08:00
/**
* sync hook
* @returns
*/
export function useSync() {
2023-09-11 22:53:04 +08:00
const { data, update, reload } = useStorage(STOKEY_SYNC, DEFAULT_SYNC);
return { sync: data, updateSync: update, reloadSync: reload };
2023-07-31 15:08:51 +08:00
}
2023-09-11 17:56:31 +08:00
2023-09-20 17:47:23 +08:00
/**
* update syncmeta hook
* @returns
*/
export function useSyncMeta() {
const { updateSync } = useSync();
2023-09-20 17:47:23 +08:00
const updateSyncMeta = useCallback(
(key) => {
updateSync((prevSync) => {
const newSyncMeta = {
...(prevSync?.syncMeta || {}),
[key]: {
...(prevSync?.syncMeta?.[key] || {}),
updateAt: Date.now(),
},
};
return { syncMeta: newSyncMeta };
});
2023-09-20 17:47:23 +08:00
},
[updateSync]
2023-09-20 17:47:23 +08:00
);
2023-09-20 17:47:23 +08:00
return { updateSyncMeta };
}
2023-09-11 17:56:31 +08:00
/**
* caches sync hook
* @param {*} url
* @returns
*/
export function useSyncCaches() {
2023-09-11 22:53:04 +08:00
const { sync, updateSync, reloadSync } = useSync();
2023-09-11 17:56:31 +08:00
const updateDataCache = useCallback(
(url) => {
updateSync((prevSync) => ({
dataCaches: {
...(prevSync?.dataCaches || {}),
[url]: Date.now(),
},
}));
2023-09-11 17:56:31 +08:00
},
[updateSync]
2023-09-11 17:56:31 +08:00
);
const deleteDataCache = useCallback(
(url) => {
updateSync((prevSync) => {
const newDataCaches = { ...(prevSync?.dataCaches || {}) };
delete newDataCaches[url];
return { dataCaches: newDataCaches };
});
2023-09-11 17:56:31 +08:00
},
[updateSync]
2023-09-11 17:56:31 +08:00
);
const dataCaches = useMemo(() => sync?.dataCaches || {}, [sync?.dataCaches]);
2023-09-11 17:56:31 +08:00
return {
dataCaches,
2023-09-11 17:56:31 +08:00
updateDataCache,
deleteDataCache,
2023-09-11 22:53:04 +08:00
reloadSync,
2023-09-11 17:56:31 +08:00
};
}