UNPKG

react-state-bucket

Version:

A lightweight and powerful package designed to manage states globally in React applications. It provides CRUD operations for your state data with ease, enabling developers to handle complex state management scenarios without the need for heavy libraries.

101 lines (100 loc) 3.29 kB
import {setCookie,getCookie}from'./Cookie.mjs';class Bucket { constructor(initial, option) { this.hooks = new Map(); this.data = new Map(); this.changes = new Map(); this.initial = initial; this.option = Object.assign({ store: "memory" }, option); } subscribe(id, hook) { if (!id.startsWith("rsb_")) throw new Error("Invalid subscription"); this.hooks.set(id, hook); } unsubscribe(id) { this.hooks.delete(id); } set(key, value, dispatch = true) { if (typeof window !== 'undefined') { value = JSON.stringify(value); if (this.option.store === 'session' || this.option.store === 'local') { let storage = this.option.store === "session" ? sessionStorage : localStorage; storage.setItem(key, value); } else if (this.option.store === 'url') { let url = new URL(window.location.href); url.searchParams.set(key, encodeURIComponent(value)); window.history.replaceState({}, '', url.toString()); } else if (this.option.store === 'cookie') { setCookie(key, value); } else { this.data.set(key, value); } this.changes.set(key, true); if (this.option.onChange) { this.option.onChange(key, value); } if (dispatch) { this.hooks.forEach(h => h()); } } } get(key) { let value; if (typeof window !== 'undefined') { if (this.option.store === 'session' || this.option.store === 'local') { let storage = this.option.store === "session" ? sessionStorage : localStorage; value = storage.getItem(key); } else if (this.option.store === 'url') { let url = new URL(window.location.href); let storedValue = url.searchParams.get(key); value = decodeURIComponent(storedValue); } else if (this.option.store === 'cookie') { value = getCookie(key); } else { value = this.data.get(key); } try { value = JSON.parse(value); } catch (error) { } } try { value = this.initial[key].parse(value); } catch (error) { } return value; } sets(state) { for (let k in state) { this.set(k, state[k], true); } this.hooks.forEach(h => h()); } get state() { const state = {}; for (let k in this.initial) { state[k] = this.get(k); } return state; } get errors() { const errors = new Map(); for (let k in this.initial) { try { // console.log(k, this.get(k as keyof IT)); this.initial[k].parse(this.get(k)); } catch (error) { errors.set(k, error.message); } } return errors; } }export{Bucket as default};//# sourceMappingURL=Bucket.mjs.map