router_resource.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //! Example: Updating components with use_resource
  2. //! -----------------
  3. //!
  4. //! This example shows how to use ReadOnlySignal to make props reactive
  5. //! when linking to it from the same component, when using use_resource
  6. use dioxus::prelude::*;
  7. #[derive(Clone, Routable, Debug, PartialEq)]
  8. enum Route {
  9. #[route("/")]
  10. Home {},
  11. #[route("/blog/:id")]
  12. Blog { id: i32 },
  13. }
  14. fn main() {
  15. dioxus::launch(App);
  16. }
  17. #[component]
  18. fn App() -> Element {
  19. rsx! {
  20. Router::<Route> {}
  21. }
  22. }
  23. // We use id: ReadOnlySignal<i32> instead of id: i32 to make id work with reactive hooks
  24. // Any i32 we pass in will automatically be converted into a ReadOnlySignal<i32>
  25. #[component]
  26. fn Blog(id: ReadOnlySignal<i32>) -> Element {
  27. async fn future(n: i32) -> i32 {
  28. n
  29. }
  30. // Because we accept ReadOnlySignal<i32> instead of i32, the resource will automatically subscribe to the id when we read it
  31. let res = use_resource(move || future(id()));
  32. match res() {
  33. Some(id) => rsx! {
  34. div {
  35. "Blog post {id}"
  36. }
  37. for i in 0..10 {
  38. div {
  39. Link { to: Route::Blog { id: i }, "Go to Blog {i}" }
  40. }
  41. }
  42. },
  43. None => rsx! {},
  44. }
  45. }
  46. #[component]
  47. fn Home() -> Element {
  48. rsx! {
  49. Link {
  50. to: Route::Blog {
  51. id: 0
  52. },
  53. "Go to blog"
  54. }
  55. }
  56. }