react-hook-form-storage
Version:
A TypeScript library for React Hook Form persist functionality
3 lines (2 loc) • 1.34 kB
JavaScript
import{useState as e,useCallback as t,useEffect as r}from"react";const s=(e,t,r)=>Object.entries(e).reduce((e,[s,o])=>t&&!t.includes(s)||r&&r.includes(s)?e:{...e,[s]:o},{}),o=(e,t={},r=!1)=>{const s=Object.entries(e),o=t;return s.reduce((e,[t,s])=>{const n=null==o?void 0:o[t];if(!n)return{...e,[t]:s};const c=r?n.deserialize:n.serialize;if(!c)return e;const a=c(s);return{...e,[t]:a}},{})},n=(n,c,{storage:a=localStorage,included:i,excluded:u,onRestore:l,onSave:d,debounce:m,dirty:f,touched:h,validate:y,serializer:b={},autoSave:g=!0}={})=>{const[v,O]=e(!1),{setValue:S,watch:j}=c,p=t((e,t)=>a.setItem(e,t),[a]),w=t(e=>a.getItem(e),[a]),z=t(e=>a.removeItem(e),[a]),I=t(async e=>{const t=s(e,i,u),r=o(t,b);await p(n,JSON.stringify(r)),null==d||d(t)},[n,i,u,d,b,p]);return r(()=>{(async()=>{try{const e=await w(n);if(e){const t=JSON.parse(e),r=s(t,i,u),n=o(r,b,!0);Object.entries(n).forEach(([e,t])=>{S(e,t,{shouldDirty:f,shouldTouch:h,shouldValidate:y})}),O(!0),null==l||l(r)}}catch(e){console.error("Failed to restore data from storage:",e)}})()},[]),r(()=>{if(!g)return;const e=j(m?((e,t)=>{let r=null;return(...s)=>{r&&clearTimeout(r),r=setTimeout(()=>e(...s),t)}})(I,m):I);return()=>e.unsubscribe()},[j,m]),{isRestored:v,save:async()=>I(c.getValues()),clear:async()=>z(n)}};export{n as useFormStorage};
//# sourceMappingURL=index.mjs.map