added useEntity and useEntityQuery hooks

This commit is contained in:
dswbx
2024-12-12 17:00:10 +01:00
parent 9d9aa7b7a5
commit 50c5adce0c
13 changed files with 456 additions and 38 deletions

View File

@@ -1,20 +1,45 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import { useApiQuery } from "ui/client";
import { Scrollable } from "ui/layouts/AppShell/AppShell";
export default function SWRAndAPI() {
const [enabled, setEnabled] = useState(false);
const { data, error, isLoading } = useApiQuery(({ data }) => data.readMany("posts"), {
enabled,
const [text, setText] = useState("");
const { data, ...r } = useApiQuery((api) => api.data.readOne("comments", 1), {
refine: (data) => data.data,
revalidateOnFocus: true
});
const comment = data ? data : null;
useEffect(() => {
setText(comment?.content ?? "");
}, [comment]);
return (
<Scrollable>
<button onClick={() => setEnabled((p) => !p)}>{enabled ? "disable" : "enable"}</button>
{error && <div>failed to load</div>}
{isLoading && <div>loading...</div>}
<pre>{JSON.stringify(r.promise.keyArray({ search: false }))}</pre>
{r.error && <div>failed to load</div>}
{r.isLoading && <div>loading...</div>}
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
{data && (
<form
onSubmit={async (e) => {
e.preventDefault();
if (!comment) return;
await r.mutate(async () => {
const res = await r.api.data.updateOne("comments", comment.id, {
content: text
});
return res.data;
});
return false;
}}
>
<input type="text" value={text} onChange={(e) => setText(e.target.value)} />
<button type="submit">submit</button>
</form>
)}
</Scrollable>
);
}

View File

@@ -0,0 +1,55 @@
import { useEffect, useState } from "react";
import { useEntity, useEntityQuery } from "ui/client/api/use-entity";
import { Scrollable } from "ui/layouts/AppShell/AppShell";
export default function SwrAndDataApi() {
return (
<div>
<DirectDataApi />
<QueryDataApi />
</div>
);
}
function QueryDataApi() {
const [text, setText] = useState("");
const { data, update, ...r } = useEntityQuery("comments", 1, {});
const comment = data ? data : null;
useEffect(() => {
setText(comment?.content ?? "");
}, [comment]);
return (
<Scrollable>
<pre>{JSON.stringify(r.key)}</pre>
{r.error && <div>failed to load</div>}
{r.isLoading && <div>loading...</div>}
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
{data && (
<form
onSubmit={async (e) => {
e.preventDefault();
if (!comment) return;
await update({ content: text });
return false;
}}
>
<input type="text" value={text} onChange={(e) => setText(e.target.value)} />
<button type="submit">submit</button>
</form>
)}
</Scrollable>
);
}
function DirectDataApi() {
const [data, setData] = useState<any>();
const { create, read, update, _delete } = useEntity("comments", 1);
useEffect(() => {
read().then(setData);
}, []);
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}