Added server-side function example

This commit is contained in:
LeMoonStar 2024-12-15 20:34:07 +01:00
parent 57369ecb38
commit 9cea4be017

View file

@ -1,4 +1,4 @@
use leptos::prelude::*; use leptos::{prelude::*, task::spawn_local};
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title}; use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
use leptos_router::{ use leptos_router::{
components::{Route, Router, Routes}, components::{Route, Router, Routes},
@ -16,7 +16,7 @@ pub fn shell(options: LeptosOptions) -> impl IntoView {
<HydrationScripts options/> <HydrationScripts options/>
<MetaTags/> <MetaTags/>
</head> </head>
<body class="text-center"> <body>
<App/> <App/>
</body> </body>
</html> </html>
@ -38,7 +38,7 @@ pub fn App() -> impl IntoView {
// content for this welcome page // content for this welcome page
<Router> <Router>
<main> <main class="text-center">
<Routes fallback=|| "Page not found.".into_view()> <Routes fallback=|| "Page not found.".into_view()>
<Route path=StaticSegment("") view=HomePage/> <Route path=StaticSegment("") view=HomePage/>
</Routes> </Routes>
@ -47,15 +47,28 @@ pub fn App() -> impl IntoView {
} }
} }
/// Server-side increment function
#[server]
pub async fn increment(count: i32) -> Result<i32, ServerFnError> {
Ok(count + 1) // Increment logic handled server-side
}
/// Renders the home page of your application. /// Renders the home page of your application.
#[component] #[component]
fn HomePage() -> impl IntoView { fn HomePage() -> impl IntoView {
// Creates a reactive value to update the button // Client-side signal for count
let count = RwSignal::new(0); let count = RwSignal::new(0);
let on_click = move |_| *count.write() += 1;
// Button click handler to call the server function
let on_click = move |_| {
let count_value = count.get();
spawn_local(async move { count.set(increment(count_value).await.unwrap()) });
};
view! { view! {
<h1 class="text-2xl font-bold">"Welcome to Leptos!"</h1> <h1 class="text-2xl font-bold mb-2">"Welcome to Leptos!"</h1>
<button class="bg-gray-200 p-2 rounded-md" on:click=on_click>"Click Me: " <span class="font-bold">{count}</span></button> <button class="bg-gray-200 p-2 rounded-md hover:bg-gray-300" on:click=on_click>
"Click Me: " <span class="font-bold">{move || count.get()}</span>
</button>
} }
} }