2024-06-18 23:39:45 +00:00
|
|
|
//! Example: Updating components with use_resource
|
|
|
|
//! -----------------
|
|
|
|
//!
|
2024-06-19 16:06:42 +00:00
|
|
|
//! This example shows how to use ReadOnlySignal to make props reactive
|
2024-06-18 23:39:45 +00:00
|
|
|
//! 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::<Route> {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-19 15:54:39 +00:00
|
|
|
// We use id: ReadOnlySignal<i32> instead of id: i32 to make id work with reactive hooks
|
|
|
|
// Any i32 we pass in will automatically be converted into a ReadOnlySignal<i32>
|
2024-06-18 23:39:45 +00:00
|
|
|
#[component]
|
|
|
|
fn Blog(id: ReadOnlySignal<i32>) -> Element {
|
|
|
|
async fn future(n: i32) -> i32 {
|
|
|
|
n
|
|
|
|
}
|
|
|
|
|
2024-06-19 15:54:39 +00:00
|
|
|
// Because we accept ReadOnlySignal<i32> instead of i32, the resource will automatically subscribe to the id when we read it
|
2024-06-18 23:39:45 +00:00
|
|
|
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"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|