0
#[derive(PartialEq, Properties)]
pub struct ItemProps {
    cost: i128,
    purchaseCallback: Callback<i32>,
    name: String,
    imgUrl: String,
    cookiesPerSecond: i128,
    itemIndex: i32,
}

#[function_component]
pub fn Item(props: &ItemProps) -> Html {
    let ItemProps {cost, purchaseCallback, name, imgUrl, cookiesPerSecond, itemIndex} = props;
    let onclick: Callback<MouseEvent> = Callback::from(move |_| {
        purchaseCallback.emit(*itemIndex);
    });

    html! {
        <div class="item">
            <img src={imgUrl.as_str()} />
            <span class="item-name">{name.as_str()}</span>
            <span class="item-cost">{cost}</span>
            <button {onclick}></button>
        </div>
    }
}

Error message:

  --> src/main.rs:20:41
   |
18 |   pub fn Item(props: &ItemProps) -> Html {
   |               -----  - let's call the lifetime of this reference `'1`
   |               |
   |               `props` is a reference that is only valid in the function body
19 |       let ItemProps {cost, purchaseCallback, name, imgUrl, cookiesPerSecond, itemIndex} = props;
20 |       let onclick: Callback<MouseEvent> = Callback::from(move |_| {
   |  _________________________________________^
21 | |         purchaseCallback.emit(*itemIndex);
22 | |     });
   | |      ^
   | |      |
   | |______`props` escapes the function body here
   |        argument requires that `'1` must outlive `'static`

I am building a component in Rust with the yew web-assembly framework. I am running into an error where when I try to use a property of the props parameter. Whenever I have a reference to one of the properties inside of the props struct I get an error saying that it "escapes the function body". I am wondering if there is a way to fix this. I split up the struct into its variables but cant use them in the html! macro or the callback. I also cant convert the itemIndex: &i32 to an i32 for the callback because of this same error.

Ken White
  • 123,280
  • 14
  • 225
  • 444
Ryan LeRoy
  • 19
  • 2
  • 1
    [`Callback`](https://docs.rs/yew/latest/yew/callback/struct.Callback.html) is internally an `Rc`, so you could just add a `let purchaseCallback = Callback::clone(purchaseCallback);` in `fn Item` (and possibly the same for `itemIndex`). – Caesar May 16 '23 at 23:15

0 Answers0