How do I get an html page in synchronous code without using reqwest::blocking?

Viewed 41

I need to make a function that will receive an HTML page from the link. Since I use the yew library, WASM does not allow me to use many custom libraries and functions. For example, the library Tokio, future and the function reqwest::blocking::get().

I had something like this code that works in the Rust test file:

pub fn get_response() {
    let link = "url";
    let response = reqwest::blocking::get(link).unwrap();
    let res = response.text().unwrap();
}

But as I said, the yew library does not allow me to use blocking::get() how do I make the same function but without using blocking::get()?

1 Answers

If you are using Yew, then your Rust code will always be running within the context of a component or in service there-of. So you should have access to a Context or at least a Scope and then can issue async tasks like so:

ctx.link().send_future(async move {
    // do your reqwest call here
});

There are slightly different but similar functions like .callback_future(), .callback_future_once(), and .send_future_batch() but are really only different in terms of how they are called or how they interact with Yew. And with almost all scope functions, these will expect to return some message to the component, since you're likely to want to update some state after receiving the response.


If you really don't want to use Yew's scope functions, or don't have a reasonable way to access them, you can use spawn_local from the wasm-bindgen-futures crate that Yew uses internally:

wasm_bindgen_futures::spawn_local(async move {
    // do your reqwest call here
})
Related