main.rs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //! Run with:
  2. //!
  3. //! ```sh
  4. //! dioxus build --features web
  5. //! cargo run --features ssr --no-default-features
  6. //! ```
  7. #![allow(non_snake_case)]
  8. use dioxus::prelude::*;
  9. use dioxus_fullstack::prelude::*;
  10. use serde::{Deserialize, Serialize};
  11. fn main() {
  12. #[cfg(feature = "web")]
  13. dioxus_web::launch_with_props(
  14. app,
  15. get_root_props_from_document().unwrap_or_default(),
  16. dioxus_web::Config::new().hydrate(true),
  17. );
  18. #[cfg(feature = "ssr")]
  19. {
  20. // Start hot reloading
  21. hot_reload_init!(dioxus_hot_reload::Config::new().with_rebuild_callback(|| {
  22. execute::shell("dioxus build --features web")
  23. .spawn()
  24. .unwrap()
  25. .wait()
  26. .unwrap();
  27. execute::shell("cargo run --features ssr --no-default-features")
  28. .spawn()
  29. .unwrap();
  30. true
  31. }));
  32. PostServerData::register().unwrap();
  33. GetServerData::register().unwrap();
  34. tokio::runtime::Runtime::new()
  35. .unwrap()
  36. .block_on(async move {
  37. let routes = serve_dioxus_application(
  38. "",
  39. ServeConfigBuilder::new(app, AppProps { count: 12345 }),
  40. );
  41. warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;
  42. });
  43. }
  44. }
  45. #[derive(Props, PartialEq, Debug, Default, Serialize, Deserialize, Clone)]
  46. struct AppProps {
  47. count: i32,
  48. }
  49. fn app(cx: Scope<AppProps>) -> Element {
  50. let mut count = use_state(cx, || cx.props.count);
  51. let text = use_state(cx, || "...".to_string());
  52. let server_context = cx.sc();
  53. cx.render(rsx! {
  54. h1 { "High-Five counter: {count}" }
  55. button { onclick: move |_| count += 10, "Up high!" }
  56. button { onclick: move |_| count -= 1, "Down low!" }
  57. button {
  58. onclick: move |_| {
  59. to_owned![text, server_context];
  60. async move {
  61. if let Ok(data) = get_server_data().await {
  62. println!("Client received: {}", data);
  63. text.set(data.clone());
  64. post_server_data(server_context, data).await.unwrap();
  65. }
  66. }
  67. },
  68. "Run a server function"
  69. }
  70. "Server said: {text}"
  71. })
  72. }
  73. #[server(PostServerData)]
  74. async fn post_server_data(cx: DioxusServerContext, data: String) -> Result<(), ServerFnError> {
  75. // The server context contains information about the current request and allows you to modify the response.
  76. cx.responce_headers_mut()
  77. .insert("Set-Cookie", "foo=bar".parse().unwrap());
  78. println!("Server received: {}", data);
  79. println!("Request parts are {:?}", cx.request_parts());
  80. Ok(())
  81. }
  82. #[server(GetServerData)]
  83. async fn get_server_data() -> Result<String, ServerFnError> {
  84. Ok("Hello from the server!".to_string())
  85. }