Function bounce::query::use_query_value
source · pub fn use_query_value<'hook, T>(
input: Rc<T::Input>
) -> impl 'hook + Hook<Output = UseQueryValueHandle<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.
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_value};
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() -> Html {
let user = use_query_value::<UserQuery>(0.into());
match user.result() {
// The result is None if the query is currently loading.
None => html! {<div>{"loading..."}</div>},
// The result is Some(Ok(_)) if the query has loaded successfully.
Some(Ok(m)) => html! {<div>{"User's name is "}{m.value.name.to_string()}</div>},
// The result is Some(Err(_)) if an error is returned during fetching.
Some(Err(e)) => html! {<div>{"Oops, something went wrong."}</div>},
}
}
Note
When used in function components and hooks, this hook is equivalent to:
pub fn use_query_value<T>(input: Rc<T::Input>) -> UseQueryValueHandle<T>
where
T: Query + 'static,
{
/* implementation omitted */
}