Function bounce::use_atom

source ·
pub fn use_atom<'hook, T>() -> impl 'hook + Hook<Output = UseAtomHandle<T>>
where T: Atom + 'static + 'hook,
Expand description

A hook to connect to an Atom.

Returns a UseAtomHandle<T>.

Example

#[derive(PartialEq, Atom)]
struct Username {
    inner: String,
}

impl Default for Username {
    fn default() -> Self {
        Self {
            inner: "Jane Doe".into(),
        }
    }
}

impl From<String> for Username {
    fn from(s: String) -> Self {
        Self { inner: s }
    }
}

impl fmt::Display for Username {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)
    }
}

#[function_component(Setter)]
fn setter() -> Html {
    let username = use_atom::<Username>();

    let on_text_input = {
        let username = username.clone();

        Callback::from(move |e: InputEvent| {
            let input: HtmlInputElement = e.target_unchecked_into();

            username.set(input.value().into());
        })
    };

    html! {
        <div>
            <input type_="text" oninput={on_text_input} value={username.to_string()} />
        </div>
    }
}

Note

When used in function components and hooks, this hook is equivalent to:

pub fn use_atom<T>() -> UseAtomHandle<T>
where
    T: Atom + 'static,
{
    /* implementation omitted */
}