From 7b728596cae206f247af73322b01c6d6b160f031 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tr=C3=A8sAbhi?= <43380238+tresabhi@users.noreply.github.com> Date: Sat, 27 Sep 2025 17:32:20 -0500 Subject: [PATCH] feat: storeDeferred --- packages/varuna/src/index.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/varuna/src/index.ts b/packages/varuna/src/index.ts index adb812cba..50f4e2ff7 100644 --- a/packages/varuna/src/index.ts +++ b/packages/varuna/src/index.ts @@ -1,5 +1,5 @@ import { produce } from "immer"; -import { merge } from "lodash-es"; +import { debounce, merge } from "lodash-es"; import { useEffect, useRef, useState } from "react"; export class Varuna { @@ -20,7 +20,6 @@ export class Varuna { let data = initial; if (this.persistence && typeof localStorage !== "undefined") { - const instance = this; const dehydrated = localStorage.getItem(this.persistence); if (dehydrated) { @@ -28,9 +27,7 @@ export class Varuna { data = merge(data, rehydrated); } - window.addEventListener("beforeunload", () => { - localStorage.setItem(this.persistence!, JSON.stringify(instance.state)); - }); + window.addEventListener("beforeunload", this.store.bind(this)); } this.initialized = true; @@ -55,7 +52,6 @@ export class Varuna { private dispatch() { const state = this.state; - console.log("dispatched"); this.listeners.forEach((callback) => callback(state)); } @@ -97,6 +93,7 @@ export class Varuna { this.assertInitialized(); this._state = state; this.dispatch(); + this.storeDeferred(); } get initial() { @@ -118,4 +115,10 @@ export class Varuna { return slice; } + + store() { + localStorage.setItem(this.persistence!, JSON.stringify(this.state)); + } + + storeDeferred = debounce(this.store.bind(this), 500); }