Retrieves the first entity from the table that matches the given filter, or null
if no entity matches.
const Component = () => {
const userTable = useTable((model: Model) => model.users);
// Retrieve the first user named 'Alice'
const { data: firstUser } = await useFirst(userTable, {
where: {
name: "Alice"
}
});
...
}
Parameter | Description |
---|---|
table
|
A table created by createTable() .
|
filterOrId
| Optional. Can be either a filter or primary id. If given, the item returned will be the first one to match. See filters. |
useFirst()
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,
// `null` if no entity matched,
// `undefined` if the query is not done yet
data: T|null|undefined;
// An error object if the query has produced an error
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: firstUser, state, error } = await useFirst(userTable, {
where: {
name: "Alice"
}
});
return (
<>
{state === "error" && <span>An error occurred: {error}</span>}
{state === "loading" && <span>Loading...</span>}
{state === "done" && <div>Alice: {firstUser.name}</div>}
</>
);
}
If no second parameter is supplied, useFirst()
will return the first item in the table.
// Retrieve the first user
const { data: firstUser } = await useFirst(userTable);
What exactly is meant by the “first” item in the table depends upon the insertion order, so the result is not exactly deterministic. Still, this is sometimes useful for tables that only ever store zero or one entity.
If an id is given as the second parameter, useFirst()
will return either the entity with a matching primary id or null
if no such entity exists.
// Retrieve the user with the "alice-uuid" uuid
const { data: alice } = await useFirst(userTable, "alice-uuid");
If a filter is provided as the second parameter, useFirst()
returns the first item that matches the filter (or null
if
no item in the table matches the filter).
// Retrieve the first user named 'Alice'
const { data: firstUser } = await useFirst(userTable, {
where: {
name: "Alice"
}
});