v1.3 - added an sqlite db and built data structure
This commit is contained in:
parent
b0fba52c0e
commit
5efdafbb97
37 changed files with 6414 additions and 1988 deletions
52
src/lib/useResource.js
Normal file
52
src/lib/useResource.js
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
useResource
|
||||
|
||||
The read hook every page uses:
|
||||
|
||||
const { data, error, loading } = useResource("/events", {
|
||||
fallback: { events: EVENTS }, // the old static module
|
||||
});
|
||||
|
||||
Deliberately small. If the site ever needs mutation, refetch on
|
||||
focus, or pagination, that's the point to reach for TanStack
|
||||
Query rather than growing this file.
|
||||
|
||||
Note the `ignore` flag rather than an AbortController: the
|
||||
request is shared and cached, so cancelling it would throw away
|
||||
work another component may still want. We just stop writing
|
||||
state after unmount.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { get } from "./api.js";
|
||||
|
||||
export function useResource(path, { ttl, fallback } = {}) {
|
||||
// Seed with the fallback so the first paint has content when one
|
||||
// is available, rather than flashing a spinner and then the same
|
||||
// data a moment later.
|
||||
const [state, setState] = useState(() => ({
|
||||
data: fallback,
|
||||
error: null,
|
||||
loading: true,
|
||||
}));
|
||||
|
||||
useEffect(() => {
|
||||
let ignore = false;
|
||||
|
||||
setState((prev) => ({ ...prev, loading: true, error: null }));
|
||||
|
||||
get(path, { ttl, fallback })
|
||||
.then((data) => {
|
||||
if (!ignore) setState({ data, error: null, loading: false });
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!ignore) setState((prev) => ({ ...prev, error, loading: false }));
|
||||
});
|
||||
|
||||
return () => {
|
||||
ignore = true;
|
||||
};
|
||||
}, [path, ttl]); // fallback is intentionally not a dependency
|
||||
|
||||
return state;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue