react-hook-effect
Version:
> Is a react-library consist of some react hooks > Hooks are for two areas: 1) for UI 2) for Web API
1 lines • 1.64 kB
JavaScript
import{useEffect,useState,useRef}from"react";const createBrowserStorageHook=r=>{const g="__REACT_HOOK_EFFECT__BROWSER_STORAGE_KEYS_",m=Math.round(1e12*Math.random()),S={getItem:e=>r.getItem(e),setItem:(e,t)=>r.setItem(e,t),clear:()=>r.clear(),removeItem:e=>r.removeItem(e),getLength:()=>r.length};return(t=null)=>{const[a,o]=useState(m),[r,s]=useState(m),[n,u]=useState(m),c=useRef();return useEffect(()=>{var e;r!==m&&(e=S.getItem(g),S.removeItem(r),c.current.delete(r),e&&(e=JSON.parse(e).filter(e=>e!==r),e=JSON.stringify(e),S.setItem(g,e)),s(m))},[r]),useEffect(()=>{if(a!==m){let e;var t=S.getItem(g),{key:r,value:s}=a,t=(e=t?(t=JSON.parse(t),JSON.stringify(t.includes(r)?t:[...t,r])):JSON.stringify([r]),S.setItem(g,e),JSON.stringify(s));S.setItem(r,t),o(m)}},[a]),useEffect(()=>{var e,t=S.getItem(g);const r=new Set;t?(e=(t=JSON.parse(t)).map(e=>{var t=S.getItem(e);return t?[e,JSON.parse(t)]:(r.add(e),null)}).filter(e=>null!==e),e=new Map(e),c.current=e,r.size&&(e=t.filter(e=>!r.has(e)),t=JSON.stringify(e),S.setItem(g,t))):c.current=new Map},[]),useEffect(()=>{var e;n!==m&&((e=S.getItem(g))&&(JSON.parse(e).forEach(e=>{S.removeItem(e)}),S.removeItem(g)),u(m))},[n]),{getItem(e){return c.current.get(e)??t},setItem(e,t){c.current.set(e,t),o({key:e,value:t})},clear(){c.current.clear(),u(!0)},removeItem(e){c.current.delete(e),s(e)},getLength(e=!1){return e?S.getLength():c?.current?.size},getKeys(){return c.current?[...c.current.keys()]:0}}}},useLocalStorage=createBrowserStorageHook(localStorage),useSessionStorage=createBrowserStorageHook(sessionStorage);export{createBrowserStorageHook,useLocalStorage,useSessionStorage};