Leptos Query
About
Leptos Query is a robust asynchronous state management library for Leptos, providing simplified data fetching, integrated reactivity, server-side rendering support, and intelligent cache management.
Heavily inspired by Tanstack Query.
Why Choose Leptos Query?
Leptos Query focuses on simplifying your data fetching process and keeping your application's state effortlessly synchronized and up-to-date. Here's how it's done:
Key Features
-
Configurable Caching & SWR: Queries are cached by default, ensuring quick access to your data. You can configure your stale and cache times per query with Stale While Revalidate (SWR) system.
-
Reactivity at Its Core: Leptos Query deeply integrates with Leptos' reactive system to transform asynchronous query fetchers into reactive Signals.
-
Server-Side Rendering (SSR) Compatibility: Fetch your queries on the server and smoothly serialize them to the client, just as you would with a Leptos Resource.
-
Efficient De-duplication: No unnecessary fetches here! If you make multiple queries with the same Key, Leptos Query smartly fetches only once.
-
Manual Invalidation: Control when your queries should be invalidated and refetched for that ultimate flexibility.
-
Scheduled Refetching: Set up your queries to refetch on a customized schedule, keeping your data fresh as per your needs.
Installation
cargo add leptos_query --optional
Then add the relevant feature(s) to your Cargo.toml
[features]
hydrate = [
"leptos_query/hydrate",
# ...
]
ssr = [
"leptos_query/ssr",
# ...
]
Quick Start
In the root of your App, provide a query client:
use leptos_query::*;
use leptos::*;
#[component]
pub fn App(cx: Scope) -> impl IntoView {
// Provides Query Client for entire app.
provide_query_client(cx);
// Rest of App...
}
Then make a query function.
NOTE:
- A query is unique per Key
K
. - A query Key type
K
must only correspond to ONE UNIQUE ValueV
Type.- Meaning a query Key type
K
cannot correspond to multipleV
Types.
- Meaning a query Key type
TLDR: Wrap your key in a Newtype when needed to ensure uniqueness.
use leptos::*;
use leptos_query::*;
use std::time::Duration;
use serde::*;
// Data type.
#[derive(Clone, Deserialize, Serialize)]
struct Monkey {
name: String,
}
// Create a Newtype for MonkeyId.
#[derive(Clone, PartialEq, Eq, Hash)]
struct MonkeyId(String);
// Monkey fetcher.
async fn get_monkey(id: MonkeyId) -> Monkey {
todo!()
}
// Query for a Monkey.
fn use_monkey_query(cx: Scope, id: impl Fn() -> MonkeyId + 'static) -> QueryResult<Monkey> {
leptos_query::use_query(
cx,
id,
get_monkey,
QueryOptions {
default_value: None,
refetch_interval: None,
resource_option: ResourceOption::NonBlocking,
// Considered stale after 5 seconds.
stale_time: Some(Duration::from_secs(5)),
// Infinite cache time.
cache_time: None,
},
)
}
Now you can use the query in any component in your app.