In Dioxus, you can ensure one reactive hook doesn't run until another has completed by leveraging the dependency array of use_effect and use_resource, and by inspecting the ResourceState of the preceding use_resource hook.
The core idea is to create a new derived signal (often using use_memo) that only changes its value once the first hook has reached a "completed" state. This derived signal then becomes a dependency for the second hook.
Let's break it down for use_effect waiting for use_resource and use_resource waiting for another use_resource.
Core Concept: ResourceState and use_memo
A use_resource hook returns a Signal<ResourceState<T, E>>. This ResourceState enum can be:
ResourceState::Pending
ResourceState::Loading
ResourceState::Complete(Result<T, E>)
We can use use_memo to derive a new signal that changes its value only when the ResourceState becomes Complete.
Scenario 1: use_effect waits for use_resource
You have a use_resource that fetches some data, and you want a use_effect to run only after that data is available (successfully or with an error).
#![allow(unused)]
use dioxus::prelude::*;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq)]
struct User {
id: u32,
name: String,
}
async fn fetch_user_by_id(id: u32) -> Result<User, String> {
tokio::time::sleep(Duration::from_secs(1)).await; // Simulate network delay
if id == 1 {
Ok(User { id: 1, name: "Alice".to_string() })
} else if id == 2 {
Err("User not found".to_string())
} else {
Ok(User { id, name: format!("User {}", id) })
}
}
fn App() -> Element {
let user_id = use_signal(|| 1u32);
// --- Hook 1: Fetch User Data ---
let user_resource = use_resource(move || fetch_user_by_id(user_id()));
// --- Derived Signal: Indicates when user_resource is Complete ---
// This `use_memo` creates a new signal that only changes when user_resource
// enters a `Complete` state. It also carries the result (Ok(data) or Err(error)).
let user_resource_completed_result = use_memo(&user_resource, |user_resource| {
match user_resource.cloned() {
ResourceState::Complete(Ok(data)) => {
Some(Ok(data)) // Successfully completed
},
ResourceState::Complete(Err(err)) => {
Some(Err(err)) // Completed with an error
},
_ => None, // Still pending/loading, so no result yet
}
});
// --- Hook 2: use_effect that runs ONLY after user_resource is complete ---
use_effect(user_resource_completed_result, move |user_completed_res| {
// user_completed_res.get() will give you the Option<Result<User, String>>
// This closure will only run when user_completed_res changes from None to Some(...)
if let Some(result) = user_completed_res.get() {
match result {
Ok(user) => {
println!("Hook 2: User data successfully loaded: {:?}", user);
// Perform actions that depend on the loaded user data
},
Err(e) => {
println!("Hook 2: User data failed to load: {}", e);
// Perform actions for error case
}
}
}
async move {} // use_effect requires an async block
});
rsx! {
div {
h1 { "User Fetcher" }
p { "User ID: {user_id}" }
button {
onclick: move |_| user_id.set(1),
"Fetch User 1 (Alice)"
}
button {
onclick: move |_| user_id.set(2),
"Fetch User 2 (Error)"
}
button {
onclick: move |_| user_id.set(3),
"Fetch User 3"
}
match user_resource.read().cloned() {
ResourceState::Pending => rsx! { p { "Loading user data..." } },
ResourceState::Loading => rsx! { p { "Loading user data..." } },
ResourceState::Complete(Ok(user)) => rsx! { p { "Loaded: {user.name}" } },
ResourceState::Complete(Err(e)) => rsx! { p { "Error: {e}" } },
}
}
}
}
// Minimal main for demonstration
fn main() {
dioxus::launch(App);
}
Explanation:
user_resource (Hook 1): This is your primary resource fetching hook.
user_resource_completed_result (use_memo):
- Its dependency is
&user_resource. This means it will re-evaluate whenever user_resource's internal state changes (Pending, Loading, Complete).
- Inside the
use_memo closure, we check match user_resource.cloned().
- Crucially, it returns
Some(Result) only when the user_resource is Complete. Otherwise, it returns None.
- This ensures that the value of
user_resource_completed_result only changes from None to Some(...) once the user_resource is finished.
use_effect(user_resource_completed_result, ...) (Hook 2):
- Its dependency is
user_resource_completed_result.
- Therefore, this
use_effect will only trigger when user_resource_completed_result changes from None to Some, which precisely means the user_resource has completed.
- Inside the
use_effect closure, you then use user_completed_res.get() to retrieve the actual Result from the completed resource.
Scenario 2: use_resource waits for another use_resource (Chaining)
This is a very common pattern where the input for one use_resource comes from the output of another use_resource.
#![allow(unused)]
use dioxus::prelude::*;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq)]
struct User {
id: u32,
name: String,
}
#[derive(Debug, Clone, PartialEq)]
struct UserProfile {
user_id: u32,
bio: String,
// ... other profile details
}
async fn fetch_user_id_from_session() -> Result<u32, String> {
tokio::time::sleep(Duration::from_secs(1)).await; // Simulate API call for session
println!("Fetched user ID from session!");
Ok(101) // Example user ID
}
async fn fetch_user_profile(user_id: u32) -> Result<UserProfile, String> {
tokio::time::sleep(Duration::from_secs(1_500)).await; // Simulate profile fetch delay
println!("Fetched profile for user ID: {}", user_id);
if user_id == 101 {
Ok(UserProfile { user_id, bio: "A Dioxus enthusiast.".to_string() })
} else {
Err("Profile not found".to_string())
}
}
fn App() -> Element {
// --- Hook 1: Fetch User ID ---
let user_id_resource = use_resource(fetch_user_id_from_session);
// --- Hook 2: Fetch User Profile, depending on user_id_resource ---
let user_profile_resource = use_resource(&user_id_resource, |user_id_res| async move {
match user_id_res.cloned() {
ResourceState::Complete(Ok(user_id)) => {
// If Hook 1 completed successfully, fetch the profile
println!("Hook 2: user_id_resource completed with ID: {}", user_id);
fetch_user_profile(user_id).await.map(Some) // Wrap in Option<T> for success or None for "not ready yet" if you want to handle it inside Ok() later
},
ResourceState::Complete(Err(e)) => {
// If Hook 1 completed with an error, propagate or handle it
println!("Hook 2: user_id_resource failed: {}", e);
Err(e).map(Some) // Propagate error
},
_ => {
// If Hook 1 is still Pending or Loading, do not run the actual fetch_user_profile.
// Return a Future that never resolves or resolves immediately with an empty/error state.
println!("Hook 2: user_id_resource not ready, returning Pending future.");
futures::future::pending().await // This is key: prevents the resource from *doing* anything
// Or you could do: futures::future::ready(Ok(None)) to indicate no profile yet
// Or: futures::future::ready(Err("Dependency not met".to_string()))
}
}
});
rsx! {
div {
h1 { "Chained Resource Example" }
h2 { "User ID Status:" }
match user_id_resource.read().cloned() {
ResourceState::Pending => rsx! { p { "Fetching user ID..." } },
ResourceState::Loading => rsx! { p { "Fetching user ID..." } },
ResourceState::Complete(Ok(id)) => rsx! { p { "User ID: {id}" } },
ResourceState::Complete(Err(e)) => rsx! { p { "Error fetching user ID: {e}" } },
}
h2 { "User Profile Status:" }
match user_profile_resource.read().cloned() {
ResourceState::Pending => rsx! { p { "Waiting for User ID..." } },
ResourceState::Loading => rsx! { p { "Loading user profile..." } },
ResourceState::Complete(Ok(Some(profile))) => rsx! {
div {
p { "Profile for User ID: {profile.user_id}" }
p { "Bio: {profile.bio}" }
}
},
ResourceState::Complete(Ok(None)) => rsx! { p { "No profile found (or dependency not met yet)." } },
ResourceState::Complete(Err(e)) => rsx! { p { "Error fetching profile: {e}" } },
}
}
}
}
fn main() {
dioxus::launch(App);
}
Explanation:
user_id_resource (Hook 1): This use_resource fetches the initial user_id.
user_profile_resource (Hook 2):
- Its first argument is
&user_id_resource. This means this use_resource will re-evaluate its inner closure whenever user_id_resource's state changes.
- Crucial Part: Inside the
async move closure:
- It reads the current
ResourceState of user_id_resource.
- If
user_id_resource is Complete(Ok(user_id)), it then proceeds to call fetch_user_profile(user_id).
- If
user_id_resource is Complete(Err(e)), it can propagate that error.
- If
user_id_resource is still Pending or Loading, it returns futures::future::pending().await. This Future never resolves, effectively telling Dioxus that this user_profile_resource is not ready to produce a value yet and should remain in a Pending (or Loading if it was already loading) state without actually running the expensive fetch_user_profile call.
This chaining pattern is very clean and idiomatic for sequential data fetching in Dioxus.