Skip to content

Commit

Permalink
fix #34: Load initial value only on first render for Text and Textare…
Browse files Browse the repository at this point in the history
…a Inputs
  • Loading branch information
PetoMPP committed Feb 15, 2024
1 parent 9e38c51 commit c539ee1
Showing 1 changed file with 49 additions and 4 deletions.
53 changes: 49 additions & 4 deletions src/components/atoms/text_input.rs
Original file line number Diff line number Diff line change
@@ -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::*;

Expand Down Expand Up @@ -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",
Expand All @@ -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::<HtmlInputElement>().ok())
{
input.set_value(
initial_state
.as_ref()
.map(|s| s.as_str())
.unwrap_or_default(),
);
}
},
(),
);
}
html! {
<Label label={props.label.clone()} error={props.error.clone()}>
<input {class} type={props.itype.as_str()} disabled={!props.enabled}
<input id={(*id).clone()} {class} type={props.itype.as_str()} disabled={!props.enabled}
placeholder={props.placeholder.clone()} autocomplete={props.autocomplete.clone()}
{oninput} value={props.value.clone()} />
{oninput}/>
</Label>
}
}
Expand Down Expand Up @@ -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! {
<Label label={props.label.clone()} error={props.error.clone()}>
<textarea id={(*id).clone()} {class} disabled={!props.enabled}
autocomplete={props.autocomplete.clone()} {oninput} value={props.value.clone()} />
autocomplete={props.autocomplete.clone()} {oninput}/>
</Label>
}
}

0 comments on commit c539ee1

Please sign in to comment.