Skip to content

Instantly share code, notes, and snippets.

@rebo
Last active November 20, 2019 07:13
Show Gist options
  • Save rebo/9f50f9f1355add9a961f29622e51bba0 to your computer and use it in GitHub Desktop.
Save rebo/9f50f9f1355add9a961f29622e51bba0 to your computer and use it in GitHub Desktop.
GraphQL backed list
use super::{Model, Msg};
use enclose::enclose as e;
use seed::{prelude::*, *};
use seed_comp_helpers::graphql_list::use_graphql_list;
use seed_comp_helpers::on_click;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)]
pub struct Country {
name: String,
currency: String,
emoji: String,
}
// A View that on clicking of the Send Query button retrieves a list of countries from
// a public graphQL server. This is then presented as a ul with an info pane showing
// on clicking individual countries.
pub fn view() -> Node<Msg> {
let graphql_query = "{countries {name currency emoji}}";
let graphql_url = "https://countries.trevorblades.com/";
let container_name = "countries";
// GraphQL List hook, manages fetching data and keeping list up to date.
let (list, graphql_control) =
use_graphql_list::<Country>(graphql_query, graphql_url, container_name);
div![
div![
button![
"Send Query",
on_click(e!((graphql_control) move |_| graphql_control.dispatch::<Msg, Model>()))
],
ul![list
.items()
.enumerate()
.map(|(idx, item)| li![
item.name,
on_click(e!( (graphql_control) move |_| graphql_control.list.select_only(idx)))
])
.collect::<Vec<_>>()],
],
div![if let Some(selected) = list.selected().next() {
info_pane(selected)
} else {
empty![]
}]
]
}
fn info_pane(country: &Country) -> Node<Msg> {
div![
h2!["Country Details"],
div![format!("Name: {}", country.name)],
div![format!("Currency: {}", country.currency)],
div![format!("Flag: {}", country.emoji)],
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment