server_function.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #![allow(non_snake_case, unused)]
  2. use dioxus::prelude::*;
  3. use dioxus_fullstack::prelude::*;
  4. fn main() {
  5. #[cfg(feature = "web")]
  6. dioxus_web::launch_cfg(app, dioxus_web::Config::new().hydrate(true));
  7. #[cfg(feature = "ssr")]
  8. {
  9. // Register the server function before starting the server
  10. DoubleServer::register().unwrap();
  11. tokio::runtime::Runtime::new()
  12. .unwrap()
  13. .block_on(async move {
  14. let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
  15. axum::Server::bind(&addr)
  16. .serve(
  17. axum::Router::new()
  18. // Serve Dioxus application automatically recognizes server functions and adds them to the API
  19. .serve_dioxus_application("", ServeConfigBuilder::new(app, ()))
  20. .into_make_service(),
  21. )
  22. .await
  23. .unwrap();
  24. });
  25. }
  26. }
  27. fn app(cx: Scope) -> Element {
  28. let mut count = use_state(cx, || 0);
  29. cx.render(rsx! {
  30. h1 { "High-Five counter: {count}" }
  31. button { onclick: move |_| count += 1, "Up high!" }
  32. button { onclick: move |_| count -= 1, "Down low!" }
  33. button {
  34. onclick: move |_| {
  35. to_owned![count];
  36. async move {
  37. // Call the server function just like a local async function
  38. if let Ok(new_count) = double_server(*count.current()).await {
  39. count.set(new_count);
  40. }
  41. }
  42. },
  43. "Double"
  44. }
  45. })
  46. }
  47. #[server(DoubleServer)]
  48. async fn double_server(number: u32) -> Result<u32, ServerFnError> {
  49. // Perform some expensive computation or access a database on the server
  50. tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  51. let result = number * 2;
  52. println!("server calculated {result}");
  53. Ok(result)
  54. }