From 7ee3dc41fc115018ccd93cdcf58a6bcbfee13e2d Mon Sep 17 00:00:00 2001 From: Chris Rogus Date: Tue, 18 Jun 2024 17:39:45 -0600 Subject: [PATCH] nonreactive examples for hooks were not compilable as written (#2337) * nonreactive examples for hooks were not compilable as written * add example demonstrating the correct usage of use_resource w router * switch to readonlysignal in the router resource example * fix readonlysignal name --------- Co-authored-by: Evan Almloff --- examples/router_resource.rs | 65 +++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 examples/router_resource.rs diff --git a/examples/router_resource.rs b/examples/router_resource.rs new file mode 100644 index 000000000..57a7f90dc --- /dev/null +++ b/examples/router_resource.rs @@ -0,0 +1,65 @@ +//! Example: Updating components with use_resource +//! ----------------- +//! +//! This example shows how to use use_reactive to update a component properly +//! when linking to it from the same component, when using use_resource + +use dioxus::prelude::*; + +#[derive(Clone, Routable, Debug, PartialEq)] +enum Route { + #[route("/")] + Home {}, + #[route("/blog/:id")] + Blog { id: i32 }, +} + +fn main() { + launch(App); +} + +#[component] +fn App() -> Element { + rsx! { + Router:: {} + } +} + +#[component] +fn Blog(id: ReadOnlySignal) -> Element { + async fn future(n: i32) -> i32 { + n + } + + // if you use the naive approach, the "Blog post {id}" below will never update when clicking links! + // let res = use_resource(move || future(id)); + + // the use_reactive hook is required to properly update when clicking links to this component, from this component + let res = use_resource(move || future(id())); + + match res() { + Some(id) => rsx! { + div { + "Blog post {id}" + } + for i in 0..10 { + div { + Link { to: Route::Blog { id: i }, "Go to Blog {i}" } + } + } + }, + None => rsx! {}, + } +} + +#[component] +fn Home() -> Element { + rsx! { + Link { + to: Route::Blog { + id: 0 + }, + "Go to blog" + } + } +}