I have an async function that will fetch data from an external API and update the component's state (if you're familiar with yew and hooks, it's a side effect). here is the working code :
fn my_component() -> Html {
let (_, dispatch) = use_store::<App>();
{
let dispatch = dispatch.clone();
use_effect_with_deps(
wasm_bindgen_futures::spawn_local(async move {
let request = Request::get("/api/endpoint").send().await;
if let Ok(response) = request {
match response.json::<MyObj>().await {
Ok(parsed_obj) => dispatch.reduce_mut(|store| store.state = parsed_obj),
Err(_) => {}
}
}
})
, ());
}
}
Now I'm trying to refactor this code, externalizing the request part into a separate module called services.
here is a snippet of the code
fn get_data_service(callback: Box<dyn Fn(MyObj)>) {
wasm_bindgen_futures::spawn_local(async move {
let request = Request::get("/api/endpoint").send().await;
if let Ok(response) = request {
match response.json::<MyObj>().await {
Ok(parsed_obj) => callbakc(parsed_obj),
Err(_) => {}
}
}
})
}
fn my_component() -> Html {
let (_, dispatch) = use_store::<App>();
{
let dispatch = dispatch.clone();
let update_state_callback = |fetched_obj| {
dispatch.reduce_mut(|store| store.state = fetched_obj)
};
use_effect_with_deps(
get_data_service(Box::new(update_state_callback)),
());
}
}
and this code is not working becuase of dispatch
which doesn't live long enough
..
how can I solve this problem and refactor my code this way ? or maybe there is a better way ?
Thanks !