main.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //! Run with:
  2. //!
  3. //! ```sh
  4. //! dx build --features web --release
  5. //! cargo run --features ssr --release
  6. //! ```
  7. use dioxus::prelude::*;
  8. use dioxus_fullstack::prelude::*;
  9. use dioxus_router::prelude::*;
  10. fn main() {
  11. let config = LaunchBuilder::<FullstackRouterConfig<Route>>::router();
  12. #[cfg(feature = "ssr")]
  13. config
  14. .incremental(
  15. IncrementalRendererConfig::default()
  16. .invalidate_after(std::time::Duration::from_secs(120)),
  17. )
  18. .launch();
  19. #[cfg(not(feature = "ssr"))]
  20. config.launch();
  21. }
  22. #[derive(Clone, Routable, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
  23. enum Route {
  24. #[route("/")]
  25. Home {},
  26. #[route("/blog/:id")]
  27. Blog { id: i32 },
  28. }
  29. #[component]
  30. fn Blog(cx: Scope, id: i32) -> Element {
  31. render! {
  32. Link { to: Route::Home {}, "Go to counter" }
  33. table {
  34. tbody {
  35. for _ in 0..*id {
  36. tr {
  37. for _ in 0..*id {
  38. td { "hello world!" }
  39. }
  40. }
  41. }
  42. }
  43. }
  44. }
  45. }
  46. #[component]
  47. fn Home(cx: Scope) -> Element {
  48. let mut count = use_state(cx, || 0);
  49. let text = use_state(cx, || "...".to_string());
  50. cx.render(rsx! {
  51. Link {
  52. to: Route::Blog {
  53. id: *count.get()
  54. },
  55. "Go to blog"
  56. }
  57. div {
  58. h1 { "High-Five counter: {count}" }
  59. button { onclick: move |_| count += 1, "Up high!" }
  60. button { onclick: move |_| count -= 1, "Down low!" }
  61. button {
  62. onclick: move |_| {
  63. to_owned![text];
  64. async move {
  65. if let Ok(data) = get_server_data().await {
  66. println!("Client received: {}", data);
  67. text.set(data.clone());
  68. post_server_data(data).await.unwrap();
  69. }
  70. }
  71. },
  72. "Run server function!"
  73. }
  74. "Server said: {text}"
  75. }
  76. })
  77. }
  78. #[server(PostServerData)]
  79. async fn post_server_data(data: String) -> Result<(), ServerFnError> {
  80. println!("Server received: {}", data);
  81. Ok(())
  82. }
  83. #[server(GetServerData)]
  84. async fn get_server_data() -> Result<String, ServerFnError> {
  85. Ok("Hello from the server!".to_string())
  86. }