router_resource.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //! Example: Updating components with use_resource
  2. //! -----------------
  3. //!
  4. //! This example shows how to use use_reactive to update a component properly
  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. launch(App);
  16. }
  17. #[component]
  18. fn App() -> Element {
  19. rsx! {
  20. Router::<Route> {}
  21. }
  22. }
  23. #[component]
  24. fn Blog(id: ReadOnlySignal<i32>) -> Element {
  25. async fn future(n: i32) -> i32 {
  26. n
  27. }
  28. // if you use the naive approach, the "Blog post {id}" below will never update when clicking links!
  29. // let res = use_resource(move || future(id));
  30. // the use_reactive hook is required to properly update when clicking links to this component, from this component
  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. }