nucleux
Version:
Simple, atomic hub for all your React application's state management needs. No providers, no boilerplate, just state that works.
68 lines (67 loc) • 2.17 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Value = void 0;
const nanoid_1 = require("nanoid");
class Value {
_value;
subscribers = new Map();
persistKey;
storage;
constructor(initialValue, persistKey, options) {
this._value = initialValue;
this.persistKey = persistKey;
if (persistKey) {
this.storage = options?.storage || localStorage;
}
this.subscribe = this.subscribe.bind(this);
this.unsubscribe = this.unsubscribe.bind(this);
this.hydrate();
}
async hydrate() {
if (this.persistKey && this.storage) {
const rawPersistedValue = await this.storage.getItem(this.persistKey);
if (rawPersistedValue) {
try {
const persistedValue = JSON.parse(rawPersistedValue);
this.value = persistedValue;
}
catch (error) {
console.error(`Could not parse value ${rawPersistedValue} for ${this.persistKey}. Error:`, error);
}
}
else {
// fire-and-forget
this.storage.setItem(this.persistKey, JSON.stringify(this.value));
}
}
}
get value() {
return this._value;
}
set value(newValue) {
if (newValue === this.value) {
return;
}
this._value = newValue;
if (newValue !== undefined && this.persistKey && this.storage) {
// fire-and-forget
this.storage.setItem(this.persistKey, JSON.stringify(newValue));
}
for (const [, subscriber] of this.subscribers) {
subscriber.callback(this.value);
}
}
subscribe(callback) {
const subId = (0, nanoid_1.nanoid)();
this.subscribers.set(subId, { callback });
return subId;
}
unsubscribe(subId) {
if (!this.subscribers.has(subId)) {
console.warn(`Subscriber ${subId} not found`);
return false;
}
return this.subscribers.delete(subId);
}
}
exports.Value = Value;