@d3vtool/hooks
Version:
Collection of custom React hooks to simplify tasks in your React projects.
2 lines (1 loc) • 1.07 kB
JavaScript
var m=function(a,t){var n=typeof Symbol=="function"&&a[Symbol.iterator];if(!n)return a;var o=n.call(a),r,i=[],u;try{for(;(t===void 0||t-- >0)&&!(r=o.next()).done;)i.push(r.value)}catch(l){u={error:l}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(u)throw u.error}}return i};import{deserialize as g}from"./utils";import{useCallback as y,useEffect as _,useId as w,useRef as p,useState as S}from"react";export function useReadPersistentState(a,t){t===void 0&&(t=g);var n=typeof window<"u",o=w(),r=p(null),i=m(S(),2),u=i[0],l=i[1],d=y(function(e){e.data.type==="storage-broadcast"&&e.data.storageData.key===a&&e.data.storageData.value&&l(e.data.storageData.value)},[a]);return _(function(){var e;if(n){try{var f=localStorage.getItem(a);if(!f)throw new Error;var v=t(f);l(v)}catch{}var h=new BroadcastChannel(o);return r.current=h,(e=r.current)===null||e===void 0||e.addEventListener("message",d),function(){var s,c;(s=r.current)===null||s===void 0||s.removeEventListener("message",d),(c=r.current)===null||c===void 0||c.close(),r.current=null}}},[]),u}
;