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_router::{
components::{Route, Router, Routes},
@ -16,7 +16,7 @@ pub fn shell(options: LeptosOptions) -> impl IntoView {
<HydrationScripts options/>
<MetaTags/>
</head>
<body class="text-center">
<body>
<App/>
</body>
</html>
@ -38,7 +38,7 @@ pub fn App() -> impl IntoView {
// content for this welcome page
<Router>
<main>
<main class="text-center">
<Routes fallback=|| "Page not found.".into_view()>
<Route path=StaticSegment("") view=HomePage/>
</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.
#[component]
fn HomePage() -> impl IntoView {
// Creates a reactive value to update the button
// Client-side signal for count
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! {
<h1 class="text-2xl font-bold">"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>
<h1 class="text-2xl font-bold mb-2">"Welcome to Leptos!"</h1>
<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>
}
}