mentorenwahl/frontend/src/routes/home/teacher_registration.rs

104 lines
3.0 KiB
Rust

use graphql_client::reqwest::post_graphql;
use web_sys::HtmlInputElement;
use yew::prelude::*;
use crate::components;
use crate::graphql;
pub enum Msg {
Submit,
Registration(Option<Vec<String>>),
}
#[derive(Properties, PartialEq)]
pub struct TeacherRegistrationProps {
pub token: String,
pub onregistered: Callback<()>,
}
pub struct TeacherRegistration {
max_students: NodeRef,
errors: Option<Vec<String>>,
}
impl Component for TeacherRegistration {
type Message = Msg;
type Properties = TeacherRegistrationProps;
fn create(_ctx: &Context<Self>) -> Self {
Self {
max_students: NodeRef::default(),
errors: None,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Submit => {
if let Some(max_students) = self
.max_students
.cast::<HtmlInputElement>()
.map(|x| x.value_as_number() as usize)
{
let client = graphql::client(Some(&ctx.props().token)).unwrap();
ctx.link().send_future(async move {
let response = post_graphql::<
graphql::mutations::register_teacher::RegisterTeacher,
_,
>(
&client,
graphql::URL.as_str(),
graphql::mutations::register_teacher::register_teacher::Variables {
max_students: max_students as i64,
},
)
.await
.unwrap();
Msg::Registration(components::graphql_errors::convert(response.errors))
});
}
false
}
Msg::Registration(errors) => {
self.errors = errors;
if self.errors.is_none() {
ctx.props().onregistered.emit(());
false
} else {
true
}
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let onsubmit = ctx.link().callback(|e: FocusEvent| {
e.prevent_default();
Msg::Submit
});
html! {
<>
<form {onsubmit}>
<div>
<label for="max_students">
{ "Maximale Anzahl von Schülern:" }
<br />
<input ref={self.max_students.clone()} type="number" id="max_students" name="max_students" min=1 />
</label>
</div>
<div>
<input type="submit" value="Submit" />
</div>
<components::graphql_errors::GraphQLErrors errors={self.errors.clone()} />
</form>
</>
}
}
}