Persistencia en sigpro
This commit is contained in:
@@ -53,9 +53,9 @@
|
||||
};
|
||||
|
||||
// -------------------------
|
||||
// --- $ = Signal puro ---
|
||||
// --- $ = Signal puro + Persistencia ---
|
||||
// -------------------------
|
||||
const $ = (initial) => {
|
||||
const $ = (initial, key = null) => {
|
||||
if (typeof initial === "function") {
|
||||
const subs = new Set();
|
||||
let cached;
|
||||
@@ -103,6 +103,18 @@
|
||||
}
|
||||
|
||||
let value = initial;
|
||||
|
||||
if (key) {
|
||||
const saved = localStorage.getItem(key);
|
||||
if (saved !== null) {
|
||||
try {
|
||||
value = JSON.parse(saved);
|
||||
} catch {
|
||||
value = saved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const subs = new Set();
|
||||
|
||||
return (...args) => {
|
||||
@@ -110,6 +122,10 @@
|
||||
const next = typeof args[0] === "function" ? args[0](value) : args[0];
|
||||
if (!Object.is(value, next)) {
|
||||
value = next;
|
||||
if (key) {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
}
|
||||
|
||||
trigger(subs);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user