@tanstack/persister
Version:
Utilities for persisting state to local storage, session storage, indexedDB, and more.
83 lines (82 loc) • 2.76 kB
JavaScript
"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const persister = require("./persister.cjs");
const defaultOptions = {
deserializer: JSON.parse,
serializer: JSON.stringify,
storage: typeof window !== "undefined" ? window.localStorage : null
};
class StoragePersister extends persister.Persister {
constructor(initialOptions) {
super(initialOptions.key);
this.setOptions = (newOptions) => {
this.options = { ...this.options, ...newOptions };
};
this.saveState = (state) => {
try {
const stateToSave = this.options.select ? this.options.select(state) : state;
this.options.storage?.setItem(
this.key,
this.options.serializer({
buster: this.options.buster,
state: stateToSave,
timestamp: Date.now()
})
);
this.options.onSaveState?.(state, this);
} catch (error) {
console.error(error);
this.options.onSaveStateError?.(error, this);
}
};
this.loadState = () => {
const stored = this.options.storage?.getItem(this.key);
if (!stored) {
return void 0;
}
try {
const parsed = this.options.deserializer(stored);
const isValidVersion = !this.options.buster || parsed.buster === this.options.buster;
const isNotExpired = !this.options.maxAge || !parsed.timestamp || Date.now() - parsed.timestamp <= this.options.maxAge;
if (!isValidVersion || !isNotExpired) {
this.options.storage?.removeItem(this.key);
return void 0;
}
const state = parsed.state;
this.options.onLoadState?.(state, this);
return state;
} catch (error) {
console.error(error);
this.options.onLoadStateError?.(error, this);
return void 0;
}
};
this.handleStorageChange = (e) => {
if (e.storageArea !== this.options.storage) {
return;
}
if (e.key === this.key && e.newValue) {
this.loadState();
}
};
this.subscribeToStorage = () => {
typeof window !== "undefined" && window.addEventListener("storage", this.handleStorageChange);
};
this.unsubscribeFromStorage = () => {
typeof window !== "undefined" && window.removeEventListener("storage", this.handleStorageChange);
};
this.clearState = (useDefaultState = false) => {
if (useDefaultState) {
this.saveState(this.options.defaultState);
} else {
this.options.storage?.removeItem(this.key);
}
};
this.options = {
...defaultOptions,
...initialOptions
};
}
}
exports.StoragePersister = StoragePersister;
//# sourceMappingURL=storage-persister.cjs.map