-
I'm trying to get a resource and save it in the client as global state. I want to achieve the following when navigation occurs:
I've achieved my goal, but my solution feels bad. I'm new to Leptos and can't find an appropriate example. Is my solution bad? How can I do this properly? #[derive(PartialEq, Serialize, Deserialize, Clone)]
pub struct User {
pub username: String,
}
#[derive(Default, Clone)]
struct GlobalState {
user: Option<User>,
}
#[component]
pub fn HomePage() -> impl IntoView {
let curr_user_res = create_resource(
|| (),
|_| async move {
let state = expect_context::<RwSignal<GlobalState>>();
match state.get().user {
None => get_user().await, // get_user() is server function that returns the User struct
Some(user) => user,
}
},
);
view! {
<Suspense fallback=move || { view! { <h1>"Loading..."</h1> } }>
{move || {
let state = expect_context::<RwSignal<GlobalState>>();
curr_user_res
.get()
.map(|curr_user| {
state.update(|it| it.user = Some(curr_user.clone()));
view! { <h1>"Welcome, "{curr_user.username}"!"</h1> }
})
}}
</Suspense>
}
} I don't like to do |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
Why not just create the resource and share it via context? Resources can be mutated/updated, if you need to change it later. Is there a reason you want to store the same data separately in a signal? |
Beta Was this translation helpful? Give feedback.
Ultimately, there are many number of ways to handle this, right?
Route
around the only pages you want to load the user data (Login and UserPage), loading the resource in the parent route and providing it to the childrenIt's your application; you can pick whichever one's appropriate for y…