main.rs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. use salvo::prelude::*;
  33. tokio::runtime::Runtime::new()
  34. .unwrap()
  35. .block_on(async move {
  36. let router = Router::new().serve_dioxus_application(
  37. "",
  38. ServeConfigBuilder::new(app, AppProps { count: 12345 }),
  39. );
  40. Server::new(TcpListener::bind("127.0.0.1:8080"))
  41. .serve(router)
  42. .await;
  43. });
  44. }
  45. }
  46. #[derive(Props, PartialEq, Debug, Default, Serialize, Deserialize, Clone)]
  47. struct AppProps {
  48. count: i32,
  49. }
  50. fn app(cx: Scope<AppProps>) -> Element {
  51. let mut count = use_state(cx, || cx.props.count);
  52. let text = use_state(cx, || "...".to_string());
  53. let server_context = cx.sc();
  54. cx.render(rsx! {
  55. h1 { "High-Five counter: {count}" }
  56. button { onclick: move |_| count += 1, "Up high!" }
  57. button { onclick: move |_| count -= 1, "Down low!" }
  58. button {
  59. onclick: move |_| {
  60. to_owned![text, server_context];
  61. async move {
  62. if let Ok(data) = get_server_data().await {
  63. println!("Client received: {}", data);
  64. text.set(data.clone());
  65. post_server_data(server_context, data).await.unwrap();
  66. }
  67. }
  68. },
  69. "Run a server function"
  70. }
  71. "Server said: {text}"
  72. })
  73. }
  74. #[server(PostServerData)]
  75. async fn post_server_data(cx: DioxusServerContext, data: String) -> Result<(), ServerFnError> {
  76. // The server context contains information about the current request and allows you to modify the response.
  77. cx.response_headers_mut()
  78. .insert("Set-Cookie", "foo=bar".parse().unwrap());
  79. println!("Server received: {}", data);
  80. println!("Request parts are {:?}", cx.request_parts());
  81. Ok(())
  82. }
  83. #[server(GetServerData)]
  84. async fn get_server_data() -> Result<String, ServerFnError> {
  85. Ok("Hello from the server!".to_string())
  86. }