mirror of
https://github.com/blitzkit/blitzkit.git
synced 2026-10-23 19:49:50 +02:00
feat: storeDeferred
This commit is contained in:
1 parent
0bf6ac33a5
commit
7b728596ca
1 file changed
+9
-6
@@ -1,5 +1,5 @@
|
|||||||
import { produce } from "immer";
|
import { produce } from "immer";
|
||||||
import { merge } from "lodash-es";
|
import { debounce, merge } from "lodash-es";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
export class Varuna<Type, Arguments = void> {
|
export class Varuna<Type, Arguments = void> {
|
||||||
@@ -20,7 +20,6 @@ export class Varuna<Type, Arguments = void> {
|
|||||||
let data = initial;
|
let data = initial;
|
||||||
|
|
||||||
if (this.persistence && typeof localStorage !== "undefined") {
|
if (this.persistence && typeof localStorage !== "undefined") {
|
||||||
const instance = this;
|
|
||||||
const dehydrated = localStorage.getItem(this.persistence);
|
const dehydrated = localStorage.getItem(this.persistence);
|
||||||
|
|
||||||
if (dehydrated) {
|
if (dehydrated) {
|
||||||
@@ -28,9 +27,7 @@ export class Varuna<Type, Arguments = void> {
|
|||||||
data = merge(data, rehydrated);
|
data = merge(data, rehydrated);
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener("beforeunload", () => {
|
window.addEventListener("beforeunload", this.store.bind(this));
|
||||||
localStorage.setItem(this.persistence!, JSON.stringify(instance.state));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.initialized = true;
|
this.initialized = true;
|
||||||
@@ -55,7 +52,6 @@ export class Varuna<Type, Arguments = void> {
|
|||||||
|
|
||||||
private dispatch() {
|
private dispatch() {
|
||||||
const state = this.state;
|
const state = this.state;
|
||||||
console.log("dispatched");
|
|
||||||
this.listeners.forEach((callback) => callback(state));
|
this.listeners.forEach((callback) => callback(state));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,6 +93,7 @@ export class Varuna<Type, Arguments = void> {
|
|||||||
this.assertInitialized();
|
this.assertInitialized();
|
||||||
this._state = state;
|
this._state = state;
|
||||||
this.dispatch();
|
this.dispatch();
|
||||||
|
this.storeDeferred();
|
||||||
}
|
}
|
||||||
|
|
||||||
get initial() {
|
get initial() {
|
||||||
@@ -118,4 +115,10 @@ export class Varuna<Type, Arguments = void> {
|
|||||||
|
|
||||||
return slice;
|
return slice;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
store() {
|
||||||
|
localStorage.setItem(this.persistence!, JSON.stringify(this.state));
|
||||||
|
}
|
||||||
|
|
||||||
|
storeDeferred = debounce(this.store.bind(this), 500);
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user