From c539ee18f46fa1436fe1087496a14adbba0fed0f Mon Sep 17 00:00:00 2001 From: PetoMPP Date: Sat, 23 Dec 2023 11:20:46 +0100 Subject: [PATCH] fix #34: Load initial value only on first render for Text and Textarea Inputs --- src/components/atoms/text_input.rs | 53 +++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/src/components/atoms/text_input.rs b/src/components/atoms/text_input.rs index d28c4bd..d9cc894 100644 --- a/src/components/atoms/text_input.rs +++ b/src/components/atoms/text_input.rs @@ -1,4 +1,8 @@ -use crate::{components::atoms::label::Label, utils::js::set_textarea_height}; +use crate::{ + components::atoms::label::Label, + utils::js::{set_textarea_height, set_textarea_text}, +}; +use wasm_bindgen::JsCast; use web_sys::HtmlInputElement; use yew::prelude::*; @@ -31,6 +35,10 @@ pub struct TextInputProps { #[function_component(TextInput)] pub fn text_input(props: &TextInputProps) -> Html { + let id = use_memo( + |_| web_sys::window().unwrap().crypto().unwrap().random_uuid()[..10].to_string(), + (), + ); let class = match &props.error { Some(_) => "input input-bordered shadow-md input-error text-error", None => "input input-bordered shadow-md", @@ -41,11 +49,32 @@ pub fn text_input(props: &TextInputProps) -> Html { cb.emit(target_element.value()); }) }); + { + let id = id.clone(); + let initial_state = props.value.clone(); + use_effect_with_deps( + move |_| { + if let Some(input) = web_sys::window() + .and_then(|w| w.document()) + .and_then(|d| d.get_element_by_id(id.as_str())) + .and_then(|e| e.dyn_into::().ok()) + { + input.set_value( + initial_state + .as_ref() + .map(|s| s.as_str()) + .unwrap_or_default(), + ); + } + }, + (), + ); + } html! { } } @@ -94,10 +123,26 @@ pub fn textarea_input(props: &TextareaInputProps) -> Html { } }) }; + { + let id = id.clone(); + let initial_state = props.value.clone(); + use_effect_with_deps( + move |_| { + set_textarea_text( + initial_state + .as_ref() + .map(|s| s.as_str()) + .unwrap_or_default(), + &id, + ) + }, + (), + ); + } html! {