createQuery allows you define a fetcher that can be auto-fetched and cached
when partnered with a signal Accessor. This creates a streamlined and high-performant
way to fetch data within your application with less effort.
The return value of a query is inteded to be used with useQuery.
A query is just a fancy wrapper that subscribes to the signals Observer. This means that it can be used for any scenario that is Promise-based - not just data-fetching.
See the features table to understand how to best utilize queries for each scenario you may have.
Creating a query requires two things:
If you pass a signal Accessor as the first argument, the query will subscribe
to that signal and auto-call the Promise provided when the signal value changes.
Likewise, the result of the Promise will then be cached until invalidated via
a mutation.
When using a query bound to a signal there is no need for creating mutations. You simply update the signal it is subscribed to.
Caching lifecycle:
When you pass in an signal-like function that is not a true Accessor, you forfeit
any auto-fetching and caching features. This means you must utilize mutations in
order to update the state via the createMutation
APIs.
createQuery only defines a query and does not actually call it. To use the
query you must pass the returned value into the useQuery hook which reads the
signal-based result.
The value returned is the result from calling the signal-tracked Accessor. This
is equivalent to the return value from the useRead hook.
| Feature | With Signal | Without Signal |
|---|---|---|
| auto-intial fetch | ✅ | ✅ |
| auto-refresh fetch | ✅ | ❌ |
| caching | ✅ | ❌ |
| requires mutation | ❌ | ✅ |
createQuery accepts the following options:
| Params | Required | Description |
|---|---|---|
Accessor<T> | Function | true | The signal to subscribe to. |
Promise<any> | true | The Promise to call when activated. |
createQuery returns the value of the Promise along with some additional properties:
| Property | Type | Description |
|---|---|---|
key | UUID | A uniqe ID to be referenced in the mutation invalidate Array. |
currentArgs | Args | The args passed into createQuery stored in a reference. |
{
"id": "",
"name": ""
}{
"id": "5d621392-a412-444d-b29b-4108ea9015cd",
"name": "User 5d621392-a412-444d-b29b-4108ea9015cd"
}