Just getting started / playing around with Rust + wasm. Here's some sample code from the Yew docs but I added a little async twist.
...
struct Model {
value: i64,
}
async fn do_async_thing() {
async_func_1().await;
log("Rust waited for a JS promise");
}
impl Component for Model {
...
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::AddOne => {
self.value += 1;
wasm_bindgen_futures::spawn_local(async {
do_async_thing().await;
// !!! how would we make this work...
// self.value += 1;
});
// changed
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let link = ctx.link();
html! {
<div>
<button onclick={link.callback(|_| Msg::AddOne)}>{ "+1" }</button>
<p>{ self.value }</p>
</div>
}
}
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
async fn async_func_1() -> JsValue;
}
fn main() {
log("Hello from Rust");
yew::start_app::<Model>();
}
The await does what I expected but the compiler doesn't want me to touch self.value
in the async block. If I want to mutate the model object after the await is finished, what is the idiomatic way to do it? Thanks for any pointers.