Skip to content

Commit

Permalink
Merge pull request #113 from Stygmates/add-query-segment-example
Browse files Browse the repository at this point in the history
Add query segment example
  • Loading branch information
ealmloff authored Sep 4, 2023
2 parents f449cdf + b321e4a commit 45e03fe
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 7 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ futures-util-preview = "0.2.2"
pretty_assertions = { version = "1.4.0", optional = true }
gloo-timers = { version = "0.2.6", features = ["futures"] }
js-sys = "0.3.64"
form_urlencoded = "1.2.0"

[profile.release]
# lto = true
Expand Down
55 changes: 48 additions & 7 deletions src/doc_examples/query_segments.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#![allow(non_snake_case, unused)]
use std::fmt::Display;

use dioxus::prelude::*;
use dioxus_router::prelude::*;

Expand All @@ -7,18 +9,57 @@ use dioxus_router::prelude::*;
#[rustfmt::skip]
enum Route {
// segments that start with ?: are query segments
#[route("/blog?:name")]
#[route("/blog?:query_params")]
BlogPost {
// You must include query segments in child variants
name: String,
query_params: BlogQuerySegments,
},
}

// Components must contain the same query segments as their corresponding variant
#[derive(Debug, Clone, PartialEq)]
struct BlogQuerySegments {
name: String,
surname: String,
}

/// The display impl needs to display the query in a way that can be parsed:
impl Display for BlogQuerySegments {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "name={}&surname={}", self.name, self.surname)
}
}

/// The query segment is anything that implements https://docs.rs/dioxus-router/latest/dioxus_router/routable/trait.FromQuery.html. You can implement that trait for a struct if you want to parse multiple query parameters.
impl FromQuery for BlogQuerySegments {
fn from_query(query: &str) -> Self {
let mut name = None;
let mut surname = None;
let pairs = form_urlencoded::parse(query.as_bytes());
pairs.for_each(|(key, value)| {
if key == "name" {
name = Some(value.clone().into());
}
if key == "surname" {
surname = Some(value.clone().into());
}
});
Self {
name: name.unwrap(),
surname: surname.unwrap(),
}
}
}

#[inline_props]
fn BlogPost(cx: Scope, name: String) -> Element {
todo!()
fn BlogPost(cx: Scope, query_params: BlogQuerySegments) -> Element {
render! {
div{"This is your blogpost with a query segment:"}
div{format!("{:?}", query_params)}
}
}

fn App(cx: Scope) -> Element {
render! { Router::<Route>{} }
}
// ANCHOR_END: route

fn main() {}
fn main() {}

0 comments on commit 45e03fe

Please sign in to comment.