This commit is contained in:
2026-04-14 21:57:45 +02:00
parent 97bc0eb527
commit c3ca59fa5a
10 changed files with 742 additions and 217 deletions

45
src/components/Fetch.js Normal file
View File

@@ -0,0 +1,45 @@
export const Fetch = ({ url, options = {}, fallback = "Cargando..." }, { children }) => {
const state = $$({ data: null, loading: true, error: null });
let controller = null;
const run = async () => {
if (controller) controller.abort();
controller = new AbortController();
state.loading = true;
state.error = null;
try {
const targetUrl = isFunc(url) ? url() : url;
const fetchOpts = {
...(isFunc(options) ? options() : options),
signal: controller.signal
};
const res = await fetch(targetUrl, fetchOpts);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const contentType = res.headers.get("content-type");
state.data = contentType?.includes("application/json")
? await res.json()
: await res.text();
} catch (err) {
if (err.name !== 'AbortError') state.error = err.message;
} finally {
state.loading = false;
}
};
if (isFunc(url)) Watch(url, run);
else run();
onUnmount(() => controller?.abort());
return Tag("div", { class: "sigpro-fetch" }, [
() => {
if (state.loading) return fallback;
if (state.error) return Tag("span", { style: "color:red" }, state.error);
if (state.data) return isFunc(children[0]) ? children[0](state.data) : children;
return null;
}
]);
};

53
src/components/Fetch2.js Normal file
View File

@@ -0,0 +1,53 @@
import { $$, Tag, isFunc } from "./sigpro.js";
const _cache = new Map();
const getStore = (key) => {
if (!_cache.has(key)) {
_cache.set(key, $$({ data: null, loading: false, error: null }));
}
return _cache.get(key);
};
export const Request = async (key, url, opts = {}) => {
const store = getStore(key);
const { body, ...rest } = opts;
store.loading = true;
store.error = null;
try {
const config = {
method: rest.method || 'GET',
headers: { 'Content-Type': 'application/json', ...rest.headers },
...rest
};
if (body) config.body = typeof body === 'object' ? JSON.stringify(body) : body;
const res = await fetch(url, config);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const result = await res.json();
store.data = result;
return result;
} catch (err) {
store.error = err.message;
throw err;
} finally {
store.loading = false;
}
};
export const Response = ({ name, loading, error }, { children }) => {
const store = getStore(name);
return Tag("div", { style: "display:contents" }, [
() => {
if (store.loading) return loading || "Cargando...";
if (store.error) return isFunc(error) ? error(store.error) : Tag("p", {}, store.error);
if (store.data) return isFunc(children[0]) ? children[0](store.data) : children;
return null;
}
]);
};