UNPKG

@guruhotel/aura-hooks

Version:

🪝 Hooks library designed by the Guruhotel team for Aura UI

1 lines 1.37 kB
import{useState as e,useCallback as t,useEffect as n}from"react";import{useWindowEvent as o}from"../use-window-event/use-window-event";function r(e){try{return JSON.parse(e)}catch(t){return e}}function a(a,i){const u="localStorage"===a?"aura-local-storage":"aura-session-storage";return function({key:s,defaultValue:l,getInitialValueInEffect:c=!0,deserialize:w=r,serialize:d=(e=>function(e,t){try{return JSON.stringify(e)}catch(e){throw new Error(`@guruhotel/aura-hooks ${t}: Failed to serialize the value`)}}(e,i))}){const f=t((e=>{if("undefined"==typeof window||!(a in window)||e)return null!=l?l:"";const t=window[a].getItem(s);return null!==t?w(t):null!=l?l:""}),[s,l]),[g,v]=e(f(c)),m=t((e=>{e instanceof Function?v((t=>{const n=e(t);return window[a].setItem(s,d(n)),window.dispatchEvent(new CustomEvent(u,{detail:{key:s,value:e(t)}})),n})):(window[a].setItem(s,d(e)),window.dispatchEvent(new CustomEvent(u,{detail:{key:s,value:e}})),v(e))}),[s]);return o("storage",(e=>{var t;e.storageArea===window[a]&&e.key===s&&v(w(null!=(t=e.newValue)?t:""))})),o(u,(e=>{e.detail.key===s&&v(e.detail.value)})),n((()=>{void 0!==l&&void 0===g&&m(l)}),[l,g,m]),n((()=>{c&&v(f())}),[]),[void 0===g?l:g,m]}}export function useLocalStorage(e){return a("localStorage","use-local-storage")(e)}export function useSessionStorage(e){return a("sessionStorage","use-session-storage")(e)}