UNPKG

react-usedrafty

Version:

📝 A React hook to auto-save and restore form state using localStorage or sessionStorage.

2 lines 1.81 kB
import{useEffect as f,useRef as p,useState as w}from"react";function U(n,l,T,S){let{useSession:h=!1,debounce:b=300,warnOnLeave:s=!1,onRestore:c,router:o}=S||{},a=h?sessionStorage:localStorage,u=`submitted:${n}`,i=p(null),m=p(!1),[O,d]=w(!1),[I,v]=w(null);f(()=>{if(typeof window!="undefined")try{if(a.getItem(u)==="true"){console.info(`[useDrafty] Skipping restore for "${n}" (submitted)`);return}let t=a.getItem(n);if(t){let r=JSON.parse(t);T(r),v(r),d(!0),c==null||c(r),console.info(`[useDrafty] Draft restored for "${n}"`)}}catch(e){console.warn("[useDrafty] Failed to load saved draft:",e)}finally{m.current=!0}},[n]),f(()=>{if(typeof window!="undefined"&&m.current)return i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{D()},b),()=>{i.current&&clearTimeout(i.current)}},[l,b]),f(()=>{if(!s)return;let e=()=>{let r=typeof s=="function"?s():s;return typeof r=="string"?r:"You have unsaved changes."},t=r=>{let g=e();return r.preventDefault(),r.returnValue=g,g};return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[s]),f(()=>{var t;if(!o)return;let e=()=>{y(),console.info(`[useDrafty] Draft cleared for "${n}" on navigation`)};if((t=o.events)!=null&&t.on)return o.events.on("routeChangeStart",e),()=>o.events.off("routeChangeStart",e);if(o.block)return o.block(()=>(e(),!0))},[o]);let D=()=>{try{a.setItem(n,JSON.stringify(l)),d(!0),a.removeItem(u)}catch(e){console.warn("[useDrafty] Failed to save draft:",e)}},y=e=>{try{a.removeItem(n),e!=null&&e.submitted?a.setItem(u,"true"):a.removeItem(u),d(!1),v(null)}catch(t){console.warn("[useDrafty] Failed to clear draft:",t)}},R=JSON.stringify(I)!==JSON.stringify(l);return{saveDraft:D,clearDraft:y,hasDraft:O,isDirty:R}}var x=U;export{x as default,U as useDrafty}; //# sourceMappingURL=index.mjs.map