@nomyx/gun-sync
Version:
A lightweight, powerful library for synchronizing application state in real-time using Gun.js.
36 lines (35 loc) • 1.26 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useGunValue = useGunValue;
const react_1 = require("react");
const context_1 = require("./context");
/**
* A lightweight, read-only hook to get a value from Gun.js.
*
* @param scope - A string to namespace the data.
* @param key - The key for the data within the scope.
* @param initialValue - The default value if none is set in the database.
* @param gunInstance - Optional Gun instance. If not provided, uses context.
* @returns The synchronized value.
*/
function useGunValue(scope, key, initialValue, gunInstance) {
const gun = gunInstance || (0, context_1.useGun)();
const [value, setValue] = (0, react_1.useState)(initialValue);
const gunNode = (0, react_1.useMemo)(() => gun.get(scope).get(key), [gun, scope, key]);
(0, react_1.useEffect)(() => {
gunNode.once((data) => {
if (data !== undefined) {
setValue(data);
}
});
const subscription = gunNode.on((data) => {
setValue(data);
});
return () => {
if (subscription && subscription.off) {
subscription.off();
}
};
}, [gunNode]);
return value;
}