pub fn use_query<'hook, T>(
input: Rc<T::Input>,
) -> impl 'hook + Hook<Output = SuspensionResult<UseQueryHandle<T>>>where
T: Query + 'static + 'hook,Available on crate feature
query only.Expand description
A hook to run a query and subscribes to its result, suspending while fetching.
A query is a state that is cached by an Input and queried automatically upon initialisation of the state and re-queried when the input changes.
Queries are usually tied to idempotent methods like GET, which means that they should be side-effect
free and can be cached.
If your endpoint modifies data, then you need to use a mutation.
§Example
use std::rc::Rc;
use std::convert::Infallible;
use bounce::prelude::*;
use bounce::query::{Query, QueryResult, use_query};
use yew::prelude::*;
use async_trait::async_trait;
#[derive(Debug, PartialEq)]
struct User {
id: u64,
name: String,
}
#[derive(Debug, PartialEq)]
struct UserQuery {
value: User
}
#[async_trait(?Send)]
impl Query for UserQuery {
type Input = u64;
type Error = Infallible;
async fn query(_states: &BounceStates, input: Rc<u64>) -> QueryResult<Self> {
// fetch user
Ok(UserQuery{ value: User { id: *input, name: "John Smith".into() } }.into())
}
}
#[function_component(Comp)]
fn comp() -> HtmlResult {
let user = use_query::<UserQuery>(0.into())?;
match user.as_ref() {
// The result is Some(Ok(_)) if the query has loaded successfully.
Ok(m) => Ok(html! {<div>{"User's name is "}{m.value.name.to_string()}</div>}),
// The result is Some(Err(_)) if an error is returned during fetching.
Err(_e) => Ok(html! {<div>{"Oops, something went wrong."}</div>}),
}
}§Note
When used in function components and hooks, this hook is equivalent to:
pub fn use_query<T>(input: Rc<T::Input>) -> SuspensionResult<UseQueryHandle<T>>
where
T: Query + 'static,
{
/* implementation omitted */
}