rustyew

How to get the value from state in Yew Rust


I have a state in Yew that looks like this:

let is_flipped: UseStateHandle<bool> = use_state(|| false);

As you can see, its type is UseStateHandle<bool>.

I want to extract its boolean value so I can toggle the state:

let onclick: Callback<MouseEvent> = {
    let is_flipped = is_flipped.clone();
    Callback::from(move |_| match is_flipped {
        true => is_flipped.set(false), // <- type error
        false => is_flipped.set(true), // <- type error
    })
};

But I am getting this error:

^^^^^ expected struct `UseStateHandle`, found `bool`

How can I obtain the boolean value contained in the state?


Solution

  • UseStateHandle implements Deref. You just need to dereference it:

    let onclick: Callback<MouseEvent> = {
        let is_flipped = is_flipped.clone();
        Callback::from(move |_| match *is_flipped {
            true => is_flipped.set(false),
            false => is_flipped.set(true),
        })
    };