@nomyx/gun-sync
Version:
A lightweight, powerful library for synchronizing application state in real-time using Gun.js.
50 lines (49 loc) • 1.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useGunState = useGunState;
const react_1 = require("react");
const context_1 = require("./context");
/**
* A React hook to synchronize a piece of state with 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 A state pair `[value, setValue]`, similar to `React.useState`.
*/
function useGunState(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) {
gunNode.put(initialValue);
}
else {
setValue(data);
}
});
const subscription = gunNode.on((data) => {
setValue(data);
});
return () => {
if (subscription && subscription.off) {
subscription.off();
}
};
}, [gunNode, initialValue]);
const updateValue = (0, react_1.useCallback)((newValue) => {
if (typeof newValue === 'function') {
gunNode.once((currentValue) => {
const result = newValue(currentValue);
gunNode.put(result);
});
}
else {
gunNode.put(newValue);
}
}, [gunNode]);
return [value, updateValue];
}