Function bounce::query::use_mutation
source · pub fn use_mutation<'hook, T>(
) -> impl 'hook + Hook<Output = UseMutationHandle<T>>where
T: Mutation + 'static + 'hook,
Available on crate feature
query
only.Expand description
A hook to run a mutation and subscribes to its result.
A mutation is a state that is not started until the run method is invoked. Mutations are usually used to modify data on the server.
Example
use std::rc::Rc;
use std::convert::Infallible;
use bounce::prelude::*;
use bounce::query::{Mutation, MutationResult, use_mutation, MutationState};
use yew::prelude::*;
use async_trait::async_trait;
use yew::platform::spawn_local;
#[derive(Debug, PartialEq)]
struct User {
id: u64,
name: String,
}
#[derive(Debug, PartialEq)]
struct UpdateUserMutation {
}
#[async_trait(?Send)]
impl Mutation for UpdateUserMutation {
type Input = User;
type Error = Infallible;
async fn run(_states: &BounceStates, _input: Rc<User>) -> MutationResult<Self> {
// updates the user information.
Ok(UpdateUserMutation {}.into())
}
}
#[function_component(Comp)]
fn comp() -> Html {
let update_user = use_mutation::<UpdateUserMutation>();
let on_click_update_user = {
let update_user = update_user.clone();
Callback::from(move |_| {
let update_user = update_user.clone();
spawn_local(
async move {
// The result is also returned to the run method, but since we will
// process the result in the render function, we ignore it here.
let _result = update_user.run(User {id: 0, name: "Jane Done".into() }).await;
}
);
})
};
match update_user.result() {
// The result is None if the mutation is currently loading or has yet to start.
None => if update_user.state() == MutationState::Idle {
html! {<div>{"Updating User..."}</div>}
} else {
html! {<button onclick={on_click_update_user}>{"Updating User"}</button>}
},
// The result is Some(Ok(_)) if the mutation has succeed.
Some(Ok(_m)) => html! {<div>{"User has been successfully updated."}</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_mutation<T>() -> UseMutationHandle<T>
where
T: Mutation + 'static,
{
/* implementation omitted */
}