pub fn use_query<'a, K, T, E, F, R>(
cx: Scope<'a>,
key: K,
fetcher: F,
) -> Query<'a, T, E, impl Fn() + 'a>Expand description
Use a query to load remote data and keep it up to date.
§Parameters
cx- The Scope of the containing componentkey- A unique key for this query. Any queries sharing this key will have the same data and status signals. If your query takes arguments, it’s expected to add them to the key tuple. Keys in your key tuple only need to implementHash. Using a key tuple is preferrable to using a formatted string because the tuple allows for invalidating groups of queries that share the same top level key. Why is this a closure instead of a value? Because I need to track the signals used in it. There is a more ergonomic implementation but it requires specialization or a change in sycamore’sHashimplementation.fetcher- The asynchronous function used to fetch the data. This needs to be static because it’s stored and automatically rerun if the data in the cache is stale or the query is invalidated.
§Signals in Keys
Currently, Sycamore uses the untracked_get function in its Hash
implementation for signals. This means changes won’t be tracked by default. If you want the
query to refetch every time the signal in the key changes, use signal.key()/signal.rc_key()
from the AsKeySignal and AsRcKeySignal traits
respectively.
§Example
let Query { data, status, refetch } = use_query(
cx,
("hello", "World"),
|| async { Result::<_, ()>::Ok("World".to_string()) }
);
§Notes
This will crash your application if two queries with the same key but different
types are used. Data is stored as Rc<dyn Any> internally and downcast for
each use_query invocation. If the type doesn’t match, it will panic. This
shouldn’t be a problem because different queries should never have exactly
the same key, but it’s worth noting.