1
0

main.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //! Run with:
  2. //!
  3. //! ```sh
  4. //! dioxus build --features web
  5. //! cargo run --features ssr
  6. //! ```
  7. #![allow(non_snake_case, unused)]
  8. use dioxus::prelude::*;
  9. use dioxus_fullstack::{launch, prelude::*};
  10. use serde::{Deserialize, Serialize};
  11. #[derive(Props, PartialEq, Debug, Default, Serialize, Deserialize, Clone)]
  12. struct AppProps {
  13. count: i32,
  14. }
  15. fn app(cx: Scope<AppProps>) -> Element {
  16. let mut count = use_state(cx, || cx.props.count);
  17. let text = use_state(cx, || "...".to_string());
  18. cx.render(rsx! {
  19. h1 { "High-Five counter: {count}" }
  20. button { onclick: move |_| count += 1, "Up high!" }
  21. button { onclick: move |_| count -= 1, "Down low!" }
  22. button {
  23. onclick: move |_| {
  24. to_owned![text];
  25. let sc = cx.sc();
  26. async move {
  27. if let Ok(data) = get_server_data().await {
  28. println!("Client received: {}", data);
  29. text.set(data.clone());
  30. post_server_data(sc, data).await.unwrap();
  31. }
  32. }
  33. },
  34. "Run a server function!"
  35. }
  36. "Server said: {text}"
  37. })
  38. }
  39. #[server(PostServerData)]
  40. async fn post_server_data(cx: DioxusServerContext, data: String) -> Result<(), ServerFnError> {
  41. // The server context contains information about the current request and allows you to modify the response.
  42. cx.response_headers_mut()
  43. .insert("Set-Cookie", "foo=bar".parse().unwrap());
  44. println!("Server received: {}", data);
  45. println!("Request parts are {:?}", cx.request_parts());
  46. Ok(())
  47. }
  48. #[server(GetServerData)]
  49. async fn get_server_data() -> Result<String, ServerFnError> {
  50. Ok("Hello from the server!".to_string())
  51. }
  52. fn main() {
  53. launch!(@([127, 0, 0, 1], 8080), app, {
  54. serve_cfg: ServeConfigBuilder::new(app, (AppProps { count: 0 })),
  55. incremental: IncrementalRendererConfig::default().invalidate_after(std::time::Duration::from_secs(120)),
  56. });
  57. }