UNPKG

react-api-utils

Version:

A React utility library for making API calls using React Query and Axios, providing context-based configuration and custom hooks for seamless integration.

32 lines (29 loc) 15.7 kB
(function(h,S){typeof exports=="object"&&typeof module<"u"?S(exports,require("react"),require("@tanstack/react-query"),require("@tanstack/react-query-persist-client"),require("@tanstack/query-async-storage-persister"),require("axios"),require("@react-native-async-storage/async-storage")):typeof define=="function"&&define.amd?define(["exports","react","@tanstack/react-query","@tanstack/react-query-persist-client","@tanstack/query-async-storage-persister","axios","@react-native-async-storage/async-storage"],S):(h=typeof globalThis<"u"?globalThis:h||self,S(h["react-api-utils"]={},h.React,h.ReactQuery,h.ReactQueryPersistClient,h.QueryAsyncStoragePersister,h.Axios,h.AsyncStorage))})(this,function(h,S,H,Fe,De,ee,Ie){"use strict";var M={exports:{}},I={};/** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var re;function qe(){if(re)return I;re=1;var p=S,y=Symbol.for("react.element"),w=Symbol.for("react.fragment"),E=Object.prototype.hasOwnProperty,R=p.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,P={key:!0,ref:!0,__self:!0,__source:!0};function b(m,u,_){var f,C={},O=null,L=null;_!==void 0&&(O=""+_),u.key!==void 0&&(O=""+u.key),u.ref!==void 0&&(L=u.ref);for(f in u)E.call(u,f)&&!P.hasOwnProperty(f)&&(C[f]=u[f]);if(m&&m.defaultProps)for(f in u=m.defaultProps,u)C[f]===void 0&&(C[f]=u[f]);return{$$typeof:y,type:m,key:O,ref:L,props:C,_owner:R.current}}return I.Fragment=w,I.jsx=b,I.jsxs=b,I}var q={};/** * @license React * react-jsx-runtime.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var te;function We(){return te||(te=1,process.env.NODE_ENV!=="production"&&function(){var p=S,y=Symbol.for("react.element"),w=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),P=Symbol.for("react.profiler"),b=Symbol.for("react.provider"),m=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),f=Symbol.for("react.suspense_list"),C=Symbol.for("react.memo"),O=Symbol.for("react.lazy"),L=Symbol.for("react.offscreen"),se=Symbol.iterator,Ne="@@iterator";function He(e){if(e===null||typeof e!="object")return null;var r=se&&e[se]||e[Ne];return typeof r=="function"?r:null}var A=p.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function d(e){{for(var r=arguments.length,t=new Array(r>1?r-1:0),n=1;n<r;n++)t[n-1]=arguments[n];Je("error",e,t)}}function Je(e,r,t){{var n=A.ReactDebugCurrentFrame,o=n.getStackAddendum();o!==""&&(r+="%s",t=t.concat([o]));var s=t.map(function(i){return String(i)});s.unshift("Warning: "+r),Function.prototype.apply.call(console[e],console,s)}}var Ke=!1,Be=!1,Ge=!1,Qe=!1,ze=!1,ue;ue=Symbol.for("react.module.reference");function Xe(e){return!!(typeof e=="string"||typeof e=="function"||e===E||e===P||ze||e===R||e===_||e===f||Qe||e===L||Ke||Be||Ge||typeof e=="object"&&e!==null&&(e.$$typeof===O||e.$$typeof===C||e.$$typeof===b||e.$$typeof===m||e.$$typeof===u||e.$$typeof===ue||e.getModuleId!==void 0))}function Ze(e,r,t){var n=e.displayName;if(n)return n;var o=r.displayName||r.name||"";return o!==""?t+"("+o+")":t}function ce(e){return e.displayName||"Context"}function x(e){if(e==null)return null;if(typeof e.tag=="number"&&d("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case E:return"Fragment";case w:return"Portal";case P:return"Profiler";case R:return"StrictMode";case _:return"Suspense";case f:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case m:var r=e;return ce(r)+".Consumer";case b:var t=e;return ce(t._context)+".Provider";case u:return Ze(e,e.render,"ForwardRef");case C:var n=e.displayName||null;return n!==null?n:x(e.type)||"Memo";case O:{var o=e,s=o._payload,i=o._init;try{return x(i(s))}catch{return null}}}return null}var j=Object.assign,W=0,le,fe,de,ve,pe,ye,ge;function he(){}he.__reactDisabledLog=!0;function er(){{if(W===0){le=console.log,fe=console.info,de=console.warn,ve=console.error,pe=console.group,ye=console.groupCollapsed,ge=console.groupEnd;var e={configurable:!0,enumerable:!0,value:he,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}W++}}function rr(){{if(W--,W===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:j({},e,{value:le}),info:j({},e,{value:fe}),warn:j({},e,{value:de}),error:j({},e,{value:ve}),group:j({},e,{value:pe}),groupCollapsed:j({},e,{value:ye}),groupEnd:j({},e,{value:ge})})}W<0&&d("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var J=A.ReactCurrentDispatcher,K;function V(e,r,t){{if(K===void 0)try{throw Error()}catch(o){var n=o.stack.trim().match(/\n( *(at )?)/);K=n&&n[1]||""}return` `+K+e}}var B=!1,$;{var tr=typeof WeakMap=="function"?WeakMap:Map;$=new tr}function Ee(e,r){if(!e||B)return"";{var t=$.get(e);if(t!==void 0)return t}var n;B=!0;var o=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var s;s=J.current,J.current=null,er();try{if(r){var i=function(){throw Error()};if(Object.defineProperty(i.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(i,[])}catch(g){n=g}Reflect.construct(e,[],i)}else{try{i.call()}catch(g){n=g}e.call(i.prototype)}}else{try{throw Error()}catch(g){n=g}e()}}catch(g){if(g&&n&&typeof g.stack=="string"){for(var a=g.stack.split(` `),v=n.stack.split(` `),c=a.length-1,l=v.length-1;c>=1&&l>=0&&a[c]!==v[l];)l--;for(;c>=1&&l>=0;c--,l--)if(a[c]!==v[l]){if(c!==1||l!==1)do if(c--,l--,l<0||a[c]!==v[l]){var T=` `+a[c].replace(" at new "," at ");return e.displayName&&T.includes("<anonymous>")&&(T=T.replace("<anonymous>",e.displayName)),typeof e=="function"&&$.set(e,T),T}while(c>=1&&l>=0);break}}}finally{B=!1,J.current=s,rr(),Error.prepareStackTrace=o}var D=e?e.displayName||e.name:"",k=D?V(D):"";return typeof e=="function"&&$.set(e,k),k}function nr(e,r,t){return Ee(e,!1)}function ar(e){var r=e.prototype;return!!(r&&r.isReactComponent)}function U(e,r,t){if(e==null)return"";if(typeof e=="function")return Ee(e,ar(e));if(typeof e=="string")return V(e);switch(e){case _:return V("Suspense");case f:return V("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case u:return nr(e.render);case C:return U(e.type,r,t);case O:{var n=e,o=n._payload,s=n._init;try{return U(s(o),r,t)}catch{}}}return""}var Y=Object.prototype.hasOwnProperty,Re={},_e=A.ReactDebugCurrentFrame;function N(e){if(e){var r=e._owner,t=U(e.type,e._source,r?r.type:null);_e.setExtraStackFrame(t)}else _e.setExtraStackFrame(null)}function ir(e,r,t,n,o){{var s=Function.call.bind(Y);for(var i in e)if(s(e,i)){var a=void 0;try{if(typeof e[i]!="function"){var v=Error((n||"React class")+": "+t+" type `"+i+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[i]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw v.name="Invariant Violation",v}a=e[i](r,i,n,t,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(c){a=c}a&&!(a instanceof Error)&&(N(o),d("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",n||"React class",t,i,typeof a),N(null)),a instanceof Error&&!(a.message in Re)&&(Re[a.message]=!0,N(o),d("Failed %s type: %s",t,a.message),N(null))}}}var or=Array.isArray;function G(e){return or(e)}function sr(e){{var r=typeof Symbol=="function"&&Symbol.toStringTag,t=r&&e[Symbol.toStringTag]||e.constructor.name||"Object";return t}}function ur(e){try{return be(e),!1}catch{return!0}}function be(e){return""+e}function me(e){if(ur(e))return d("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",sr(e)),be(e)}var Te=A.ReactCurrentOwner,cr={key:!0,ref:!0,__self:!0,__source:!0},Pe,Ce;function lr(e){if(Y.call(e,"ref")){var r=Object.getOwnPropertyDescriptor(e,"ref").get;if(r&&r.isReactWarning)return!1}return e.ref!==void 0}function fr(e){if(Y.call(e,"key")){var r=Object.getOwnPropertyDescriptor(e,"key").get;if(r&&r.isReactWarning)return!1}return e.key!==void 0}function dr(e,r){typeof e.ref=="string"&&Te.current}function vr(e,r){{var t=function(){Pe||(Pe=!0,d("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",r))};t.isReactWarning=!0,Object.defineProperty(e,"key",{get:t,configurable:!0})}}function pr(e,r){{var t=function(){Ce||(Ce=!0,d("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",r))};t.isReactWarning=!0,Object.defineProperty(e,"ref",{get:t,configurable:!0})}}var yr=function(e,r,t,n,o,s,i){var a={$$typeof:y,type:e,key:r,ref:t,props:i,_owner:s};return a._store={},Object.defineProperty(a._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(a,"_self",{configurable:!1,enumerable:!1,writable:!1,value:n}),Object.defineProperty(a,"_source",{configurable:!1,enumerable:!1,writable:!1,value:o}),Object.freeze&&(Object.freeze(a.props),Object.freeze(a)),a};function gr(e,r,t,n,o){{var s,i={},a=null,v=null;t!==void 0&&(me(t),a=""+t),fr(r)&&(me(r.key),a=""+r.key),lr(r)&&(v=r.ref,dr(r,o));for(s in r)Y.call(r,s)&&!cr.hasOwnProperty(s)&&(i[s]=r[s]);if(e&&e.defaultProps){var c=e.defaultProps;for(s in c)i[s]===void 0&&(i[s]=c[s])}if(a||v){var l=typeof e=="function"?e.displayName||e.name||"Unknown":e;a&&vr(i,l),v&&pr(i,l)}return yr(e,a,v,o,n,Te.current,i)}}var Q=A.ReactCurrentOwner,we=A.ReactDebugCurrentFrame;function F(e){if(e){var r=e._owner,t=U(e.type,e._source,r?r.type:null);we.setExtraStackFrame(t)}else we.setExtraStackFrame(null)}var z;z=!1;function X(e){return typeof e=="object"&&e!==null&&e.$$typeof===y}function Oe(){{if(Q.current){var e=x(Q.current.type);if(e)return` Check the render method of \``+e+"`."}return""}}function hr(e){return""}var Se={};function Er(e){{var r=Oe();if(!r){var t=typeof e=="string"?e:e.displayName||e.name;t&&(r=` Check the top-level render call using <`+t+">.")}return r}}function xe(e,r){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var t=Er(r);if(Se[t])return;Se[t]=!0;var n="";e&&e._owner&&e._owner!==Q.current&&(n=" It was passed a child from "+x(e._owner.type)+"."),F(e),d('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',t,n),F(null)}}function je(e,r){{if(typeof e!="object")return;if(G(e))for(var t=0;t<e.length;t++){var n=e[t];X(n)&&xe(n,r)}else if(X(e))e._store&&(e._store.validated=!0);else if(e){var o=He(e);if(typeof o=="function"&&o!==e.entries)for(var s=o.call(e),i;!(i=s.next()).done;)X(i.value)&&xe(i.value,r)}}}function Rr(e){{var r=e.type;if(r==null||typeof r=="string")return;var t;if(typeof r=="function")t=r.propTypes;else if(typeof r=="object"&&(r.$$typeof===u||r.$$typeof===C))t=r.propTypes;else return;if(t){var n=x(r);ir(t,e.props,"prop",n,e)}else if(r.PropTypes!==void 0&&!z){z=!0;var o=x(r);d("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",o||"Unknown")}typeof r.getDefaultProps=="function"&&!r.getDefaultProps.isReactClassApproved&&d("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function _r(e){{for(var r=Object.keys(e.props),t=0;t<r.length;t++){var n=r[t];if(n!=="children"&&n!=="key"){F(e),d("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",n),F(null);break}}e.ref!==null&&(F(e),d("Invalid attribute `ref` supplied to `React.Fragment`."),F(null))}}var ke={};function Ae(e,r,t,n,o,s){{var i=Xe(e);if(!i){var a="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(a+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var v=hr();v?a+=v:a+=Oe();var c;e===null?c="null":G(e)?c="array":e!==void 0&&e.$$typeof===y?(c="<"+(x(e.type)||"Unknown")+" />",a=" Did you accidentally export a JSX literal instead of a component?"):c=typeof e,d("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",c,a)}var l=gr(e,r,t,o,s);if(l==null)return l;if(i){var T=r.children;if(T!==void 0)if(n)if(G(T)){for(var D=0;D<T.length;D++)je(T[D],e);Object.freeze&&Object.freeze(T)}else d("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else je(T,e)}if(Y.call(r,"key")){var k=x(e),g=Object.keys(r).filter(function(wr){return wr!=="key"}),Z=g.length>0?"{key: someKey, "+g.join(": ..., ")+": ...}":"{key: someKey}";if(!ke[k+Z]){var Cr=g.length>0?"{"+g.join(": ..., ")+": ...}":"{}";d(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`,Z,k,Cr,k),ke[k+Z]=!0}}return e===E?_r(l):Rr(l),l}}function br(e,r,t){return Ae(e,r,t,!0)}function mr(e,r,t){return Ae(e,r,t,!1)}var Tr=mr,Pr=br;q.Fragment=E,q.jsx=Tr,q.jsxs=Pr}()),q}var ne;function Ye(){return ne||(ne=1,process.env.NODE_ENV==="production"?M.exports=qe():M.exports=We()),M.exports}var ae=Ye();const ie=S.createContext(null),Me={timeout:1e4},Le={defaultOptions:{queries:{staleTime:5*60*1e3,retry:3,refetchOnWindowFocus:!1}}},Ve=({baseURL:p,axiosConfig:y={},queryClientConfig:w={},children:E})=>{const R=ee.create({baseURL:p,...Me,...y}),P=new H.QueryClient({...Le,...w}),b=De.createAsyncStoragePersister({storage:Ie});return ae.jsx(ie.Provider,{value:{axiosInstance:R},children:ae.jsx(Fe.PersistQueryClientProvider,{client:P,persistOptions:{persister:b},children:E})})},$e=()=>{const p=S.useContext(ie);if(!p)throw new Error("useAPIHelper must be used within APIHelperProvider");return p},oe=async(p,y,w,E)=>{var R,P,b,m;try{return(await p.request({url:w,method:y,...E})).data}catch(u){if(ee.isAxiosError(u)){const _=u;throw{message:((P=(R=_.response)==null?void 0:R.data)==null?void 0:P.message)||_.message,status:((b=_.response)==null?void 0:b.status)||500,data:((m=_.response)==null?void 0:m.data)||null}}throw{message:u.message||"An unknown error occurred",status:500}}};function Ue({url:p,params:y,queryKey:w,axiosOptions:E,method:R,onSuccess:P,onError:b,...m}){const{axiosInstance:u}=$e(),_=w||[p,...y?Object.values(y):[]],f=H.useQuery({queryKey:_,queryFn:async()=>await oe(u,"GET",p,{params:y,...E}),enabled:R==="GET",...m}),C=H.useMutation({mutationFn:async O=>await oe(u,R,p,{data:O,params:y,...E}),onSuccess:P,onError:b});return R==="GET"?f:C}h.ApiHelperProvider=Ve,h.useApiHelper=Ue,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=react-api-utils-umd.js.map