Skip to content

How Do I Make Text Input Work (Documentation Incorrect Multiple Places) #3172

@patientplatypus6

Description

@patientplatypus6

How do I make a simple text box work? Well...I took a look at the documentation here - https://yew.rs/docs/concepts/html/events and said, fair enough -

use yew::prelude::*;
use wasm_bindgen_futures::spawn_local;
use wasm_bindgen::JsCast;
use web_sys::{EventTarget, HtmlInputElement};
// use yew::{html, ChangeData, Html, InputData};
use reqwest::header::USER_AGENT;
use std::collections::HashMap;
use yew_style_in_rs::*;
use super::super::css;

pub struct Home{
    test_string: String,
    stl: HashMap<String,String>
}

pub enum Msg {
    TestString(String)
}

async fn get_test(ticker_symbol: String) -> Result<(), reqwest::Error> {
  println!("inside get test");
  let url = "http://localhost:8000/trading/".to_string() + ticker_symbol.as_str();

  let client = reqwest::Client::new();
  let res = client
    .get(url)
    .send()
    .await?;
  let body = res.text().await?;
  println!("value of body: {:?}", body.clone());

  log::info!("{}", body);

  Ok(())
}

impl Component for Home {
    type Message = Msg;
    type Properties = ();

    fn create(_ctx: &Context<Self>) -> Self {
        log::info!("inside the create function");
        spawn_local(async{
          let test = get_test("AAPL".to_string()).await;
        });
        
        Self {test_string: "somethingsomething".to_string(), stl: css::home::styles()}
    }

    fn update(&mut self, _ctx: &Context<Self>, msg:Self::Message) -> bool {
      match msg {
        Msg::TestString(test_value) => {
          log::info!("inside update for Msg::TestString");
          log::info!("this is the value of test_value in update {:?}", test_value);
          false
        }
      }
    }

    fn view(&self, _ctx: &Context<Self>) -> Html {
      
      let input_value_handle = use_state(String::default);
      let input_value = (*input_value_handle).clone();

      let on_cautious_change = {
          let input_value_handle = input_value_handle.clone();

          Callback::from(move |e: Event| {
              // When events are created the target is undefined, it's only
              // when dispatched does the target get added.
              let target: Option<EventTarget> = e.target();
              // Events can bubble so this listener might catch events from child
              // elements which are not of type HtmlInputElement
              let input = target.and_then(|t| t.dyn_into::<HtmlInputElement>().ok());

              if let Some(input) = input {
                  input_value_handle.set(input.value());
              }
          })
      };

      html! {
        <div style={self.stl["main"].clone()}>
          <div style={self.stl["title"].clone()} class="titleheader">
            {"Asset Paper Trading"}
          </div>
          <div>
            { "hi" }
            <label for="cautious-input">
                { "My cautious input:" }
                <input onchange={on_cautious_change}
                    id="cautious-input"
                    type="text"
                    value={input_value.clone()}
                />
            </label>
          </div>
        </div>
      }
    }
}

Which results in the following error -

error[E0614]: type `impl Hook<Output = UseStateHandle<String>> + '_` cannot be dereferenced
  --> src/pages/home.rs:63:25
   |
63 |       let input_value = (*input_value_handle).clone();
   |                         ^^^^^^^^^^^^^^^^^^^^^

error[E0599]: no method named `clone` found for opaque type `impl Hook<Output = UseStateHandle<String>> + '_` in the current scope
  --> src/pages/home.rs:66:55
   |
66 |           let input_value_handle = input_value_handle.clone();
   |                                                       ^^^^^ method not found in `impl Hook<Output = UseStateHandle<String>> + '_`

Some errors have detailed explanations: E0599, E0614.
For more information about an error, try `rustc --explain E0599`.
warning: `yew_page` (lib) generated 2 warnings
error: could not compile `yew_page` due to 2 previous errors; 2 warnings emitted
2023-03-19T19:42:03.406018Z ERROR ❌ error
error from HTML pipeline

Caused by:
    0: error from asset pipeline
    1: error during cargo build execution
    2: cargo call returned a bad status

Ok - So I don't understand that error. There's also this example - https://github.com/yewstack/yew/blob/master/examples/password_strength/src/text_input.rs, but it looks like it's deprecated, or you should be using the above.

How do I fix this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions