Retrieves one entity from the table.
This is similar to useFirst()
in the sense that it retrieves only the first matching entity, but:
This makes it perfect for retrieving entities by their primary id, which are unique by default.
const Component = () => {
const userTable = useTable((model: Model) => model.users);
// Retrieve alice by UUID
const { data: alice } = await one(userTable, "alice-uuid");
...
}
Parameter | Description |
---|---|
table
|
The table created by createTable() .
|
filterOrId
| Either a filter or an id. The item returned will be the first one to match. See filters. |
useOne()
is asynchronous, which means the query doesn’t return your values immediately.
Instead, it returns an object containing the current query state, the data (if present), and zero or one error (if your query threw an error).
type QueryResult<T> {
// The item if successful,
// or `undefined` if the query is not done yet
data: T|undefined;
// An error object if the query has produced an error
// (like if no item has been found)
error: Error|undefined;
// The current state of the query
state: "loading"|"done"|"error";
}
You can use the loading state to display loading indicators while you wait for your query to complete:
const Component = () => {
const userTable = useTable((model: Model) => model.users);
const { data: alice } = await one(userTable, "alice-uuid");
return (
<>
{state === "error" && <span>An error occurred: {error}</span>}
{state === "loading" && <span>Loading...</span>}
{state === "done" && <div>Alice: {alice.name}</div>}
</>
);
}
In case an id is given as the second parameter, useOne()
will return either the entity with a matching primary id,
or return an error as detailed above.
// Retrieve alice by UUID
const { data: alice } = await one(userTable, "alice-uuid");
If the second parameter is a filter, useOne()
returns the item that matches the filter,
or return an error if no / more than one item is available.
// Retrieve alice by UUID (with filter this time!)
const { data: alice } = await one(userTable, {
where: {
id: "alice-uuid"
}
});