fetch-react-hook
Version:
Performant, flexible and extensible fetch library for React Hooks
236 lines (230 loc) • 6.45 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/hooks/useFetch.ts
import { useEffect, useState } from "react";
// src/provider/index.tsx
import { createContext, useContext } from "react";
// src/utils/index.ts
var cache = /* @__PURE__ */ new Map();
var MemoryCacheStrategy = class {
setItem(key, data) {
cache.set(key, data);
}
getItem(key) {
return cache == null ? void 0 : cache.get(key);
}
removeItem(key) {
return cache.delete(key);
}
clear() {
cache.clear();
}
};
var LocalStorageCacheStrategy = class {
setItem(key, data) {
localStorage.setItem(key, JSON.stringify(data));
}
getItem(key) {
const data = localStorage.getItem(key);
return JSON.parse(data);
}
removeItem(key) {
localStorage.removeItem(key);
return true;
}
clear() {
localStorage.clear();
}
};
// src/provider/index.tsx
import { jsx } from "react/jsx-runtime";
var FetchContext = createContext({});
var FetchProvider = ({
children,
cacheStrategy = new MemoryCacheStrategy()
}) => {
return /* @__PURE__ */ jsx(FetchContext.Provider, { value: { cacheStrategy }, children });
};
var useFetchContext = () => useContext(FetchContext);
var provider_default = FetchProvider;
// src/hooks/useFetch.ts
var defaultsConfigs = {
keepDefaultParams: true,
requestOptions: void 0
};
var useFetch = (fetcher, {
autoFetch = true,
enableLoading = true,
initialData,
onSuccess = () => null,
defaultParams,
beforeAutoFetch = () => void 0,
onError = () => null,
onFinish = () => null,
setMessage = (res) => res == null ? void 0 : res.message,
onDataSetter,
defaultStatus,
catchKey,
onCache = () => null,
justCache = false,
cacheStrategy
} = {}) => {
const { cacheStrategy: providerCacheStrategy } = useFetchContext();
const { getItem, setItem } = cacheStrategy || providerCacheStrategy || {};
const getDefaultStatus = () => {
if (defaultStatus)
return defaultStatus;
if (!enableLoading)
return "success";
return autoFetch ? "loading" : "success";
};
const [status, setStatus] = useState(getDefaultStatus);
const [data, setData] = useState(initialData);
const sendFetch = (_0, ..._1) => __async(void 0, [_0, ..._1], function* (data2, configs = defaultsConfigs) {
const { keepDefaultParams, requestOptions } = configs;
const mergedData = mergeData(
keepDefaultParams ? defaultParams : void 0,
data2
);
try {
const catchData = getDataFromCatch();
if (catchData) {
handleCatchData(catchData);
return { status: "success" };
}
if (enableLoading)
setStatus("loading");
const res = yield fetcher(mergedData, requestOptions);
if (onDataSetter) {
const callBackData = onDataSetter(res);
if (callBackData)
handleCatchResponse(callBackData);
}
handleSuccessRequest(res, mergedData);
return {
status: "success",
response: res,
message: setMessage(res)
};
} catch (e) {
handleErrorRequest(e, mergedData);
throw e;
}
});
const handleCatchResponse = (data2) => {
if (catchKey) {
setItem(catchKey, data2);
onCache(data2);
}
!justCache && setData(data2);
};
const handleCatchData = (data2) => {
onCache(data2);
!justCache && setData(data2);
};
const handleFetch = (data2, configs) => __async(void 0, null, function* () {
return yield sendFetch(data2, configs);
});
const getDataFromCatch = () => {
if (catchKey)
return getItem(catchKey);
return void 0;
};
const mergeData = (defaultParams2, data2) => {
if (defaultParams2 && data2) {
if (typeof data2 == "object") {
return __spreadValues(__spreadValues({}, defaultParams2), data2);
}
if (Array.isArray(data2) && Array.isArray(defaultParams2)) {
return [...defaultParams2, ...data2];
}
}
if (data2)
return data2;
return defaultParams2;
};
const handleSuccessRequest = (res, payload) => {
setStatus("success");
onSuccess(res, payload);
onFinish(setMessage(res), { status: "success", response: res, payload });
};
const handleErrorRequest = (e, payload) => {
onError(e, payload);
onFinish(e.message, { status: "error", response: void 0, payload });
setStatus("error");
};
useEffect(() => {
if (catchKey) {
const catchData = getDataFromCatch();
if (catchData) {
handleCatchData(catchData);
setStatus("success");
} else {
if (autoFetch) {
handleFetch(beforeAutoFetch());
}
}
} else {
if (autoFetch) {
handleFetch(beforeAutoFetch());
}
}
}, []);
const handleSetData = (newValue) => {
setData(newValue);
if (catchKey)
setItem(catchKey, newValue);
};
return {
isPending: status === "loading",
isError: status == "error",
data,
reFetch: handleFetch,
status,
setData: handleSetData
};
};
var useFetch_default = useFetch;
// src/index.ts
var src_default = useFetch_default;
export {
provider_default as FetchProvider,
LocalStorageCacheStrategy,
MemoryCacheStrategy,
src_default as default
};
//# sourceMappingURL=index.mjs.map