#Hook for component first render

6 messages · Page 1 of 1 (latest)

faint wasp
#

I have a component that goes in and out of the dom. When it comes into the DOM I would like to execute a javascript function via wasm-bindgen. How do I know when the component is available in the DOM? Is there a hook for that?

long geyser
#
use_effect(cx, (), move |_| {
   // mounted!
   async move {}
});
faint wasp
#

That seems too early. The code is executed but the component is not yet in the DOM. In fact, it is not even in the currently active tree.

tall slate
# faint wasp That seems too early. The code is executed but the component is not yet in the D...

To be clear the mounted code should be inside of the future, not above it
For example this code gets an element that is mounted

// [dependencies]
// dioxus = { git = "https://github.com/DioxusLabs/dioxus" }
// dioxus-web = { git = "https://github.com/DioxusLabs/dioxus" }
// web-sys = { version = "0.3.61", features = ["Window", "Document", "Element"] }

use dioxus::prelude::*;
use web_sys::{console, window};

fn main() {
    dioxus_web::launch(app);
}

fn app(cx: Scope) -> Element {
    use_effect(cx, (), |_| async {
        let document = window().unwrap().document();
        let element = document.unwrap().get_element_by_id("my_comp").unwrap();
        console::log_1(&element.into());
    });

    cx.render(rsx! {
        div {
            id: "my_comp",
        }
    })
}
faint wasp
#

Ok, I misunderstood because of the location of the comment. Now it works. Thanks!