I am trying to get a grip on Yew with a simple form input page.
//... imports
// I have redacted some code. RecipeItemProps is a simple three string struct
#[derive(Properties, PartialEq)]
pub struct RecipeFormProps {
pub ingredients: Vec<RecipeItemProps>,
}
#[function_component]
fn RecipeForm(props: &RecipeFormProps) -> Html {
let app_state = use_state(|| Vec::from(props.ingredients.clone()));
let add_ingridient_callback = {
let app_state = app_state.clone();
Callback::from(move |event: SubmitEvent| {
let target: EventTarget = event.target().unwrap();
let form = target.dyn_into::<HtmlFormElement>().ok();
if let Some(form) = form {
let form_data = FormData::new_with_form(&form).unwrap();
let name: JsValue = form_data.get("ingridient");
let amount: JsValue = form_data.get("amount");
let quantity: JsValue = form_data.get("quantity");
let mut myvec = app_state.to_vec();
myvec.push(RecipeItemProps {
name: name.as_string().unwrap(),
amount: amount.as_string().unwrap(),
quantity: quantity.as_string().unwrap(),
});
app_state.set(myvec);
}
event.prevent_default();
})
};
// I generate html here
However, I would like to reset form input fields in add_ingridient_callback
on submit. I cannot figure out how to actually do this. In react event.target.reset()
would achieve this. How could I manage this in yew?
There is a method in HtmlFormElement
called reset
which resets the form inputs.
if let Some(form) = form {
let form_data = FormData::new_with_form(&form).unwrap();
let name: JsValue = form_data.get("ingridient");
let amount: JsValue = form_data.get("amount");
let quantity: JsValue = form_data.get("quantity");
web_sys::console::log_1(&name);
web_sys::console::log_1(&amount);
web_sys::console::log_1(&quantity);
let mut myvec = app_state.to_vec();
myvec.push(RecipeItemProps {
name: name.as_string().unwrap(),
amount: amount.as_string().unwrap(),
quantity: quantity.as_string().unwrap(),
});
// Inserted reset
form.reset();
Why is missed this before, I cannot say. It is literally the same code as in the example.