Rust Yew, use_state<'hook, T, F>

83 Views Asked by At

I am trying to impl a hook in Yew:

pub fn get_toggle_key(v: Vec<Video>, video_index: UseStateHandle<usize>) -> Callback<KeyboardEvent> {
    

    let videos = v.clone();
    let current_video_index =  video_index;
    let current_video_index = use_state(|| 0);

    Callback::from(move |event: KeyboardEvent| {
        if event.key() == "w" || event.key() == "s" {
            let current_index = current_video_index.get();
//... more code ... 

I get this error message on last line .get():

error[E0599]: no method named `get` found for opaque type `impl Hook<Output = yew::UseStateHandle<{integer}>> + '_` in the current scope
  --> src/components/organisms/keydown_logic.rs:16:53
   |
16 |             let current_index = current_video_index.get();
   |                                                     ^^^ method not found in `impl Hook<Output = UseStateHandle<{integer}>>`


I have successfully used the use_state(|| 0); function with .clone() here: github

But when I put it inside a function I cannot make it work. Any solutions, or suggestions why?

Best regards

I tried let current_index = current_video_index.clone();

1

There are 1 best solutions below

0
Martin Schultz Kristensen On

I successfully got it to work:

Here is the code:

use crate::components::molecules::video_list::Video;
use yew::prelude::*;



// Handle keydown events to switch videos
pub fn get_toggle_key(v: &Vec<Video>, video_index: UseStateHandle<usize>) -> Callback<KeyboardEvent> {
    

    let videos = v.clone();
    let current_video_index =  video_index;
    //let current_video_index = use_state(|| 0);

    Callback::from(move |event: KeyboardEvent| {
        if event.key() == "w" || event.key() == "s" {
            let current_index = current_video_index.clone();
            let new_index = match event.key().as_str() {
                "w" => {
                    let next_index = *current_index + 1;
                    if next_index >= videos.len() {
                        0
                    } else {
                        next_index
                    }
                }
                "s" => {
                    let prev_index = *current_index as i32 - 1;
                    if prev_index < 0 {
                        (videos.len() - 1) as usize
                    } else {
                        prev_index as usize
                    }
                }
                _ => *current_index,
            };
            current_index.set(new_index);
            let audio = web_sys::HtmlAudioElement::new_with_src("static/button-124476.mp3").unwrap();
            let _ = audio.play();
        }
    })
}

You can find it also here in this Link I tried to wrap my head around the docs, and I simply think the location was wrong. "Hooks can only be used in the following locations: Top-level of a function/hook." from yew docs