DioxusLabs / dioxus

Fullstack app framework for web, desktop, mobile, and more.
https://dioxuslabs.com
Apache License 2.0
20.14k stars 772 forks source link

`use_request`: a `use_resource` alternative for manual trigger #2539

Open gusinacio opened 2 months ago

gusinacio commented 2 months ago

Feature Request

I'd like to have a "use_resource" that allows me to trigger a query only when a button is pushed.

Currently, I'm using the following code to achieve this:

enum QueryState<R> {
    Pending,
    Fetching,
    Result(R),
}
let mut signal_result = use_signal::<QueryState<Result<String, ServerFnError>>>(|| QueryState::Pending);

let request_string = move || {
    *signal_result.write() = QueryState::Fetching;
    spawn(async move {
        let result = // perform a async server function;
        *signal_result.write() = QueryState::Result(result);
    });
};
rsx! {
    button {
        onclick: move |_| {
            request_string();
        },
        "Click me"
    }
}

The problem with this approach is that I have to keep track of all the state information by myself. Also, it's hard to use in multiple places and I feel that this is a good feature for Dioxus

rogusdev commented 2 months ago

I am also interested in this, but I suspect the answer to your question may simply be to convert what you have above into a hook that can then be reused. I had a discussion about this with Evan (in the midst of many other topics): https://discord.com/channels/899851952891002890/1238219898795196499/1242814582746124328 and he suggested looking at https://dioxuslabs.com/learn/0.5/cookbook/state/custom_hooks for doing what you (and I) described.

It's worth noting that use_resource already has some potentially relevant states: https://github.com/DioxusLabs/dioxus/blob/487570d89751b34bbfd5e9b5ff1e0fd3780bf332/packages/hooks/src/use_resource.rs#L132 and the difference is in the logic of how it automatically starts the async task immediately rather than waiting until some trigger.