Replies: 1 comment 1 reply
-
Can you please format your post such that it uses code blocks properly? I cannot understand your issue because of the misformatted text |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello everyone,
I am encountering an issue with managing the application state in my Yew application.
In my app, I use AppStateContext to wrap around the Route component, and I update the AppState (which includes the user information) in the Login component using:
rust
复制代码
let app_state = use_context::().expect("no context found");
app_state.borrow_mut().user = Some(UserInfo::new(login_res.user, login_res.token));
console::log_1(&JsValue::from_str(&format!("{:?}", app_state.borrow())));
gloo::timers::future::TimeoutFuture::new(5000).await;
web_sys::window().unwrap().location().set_href("/").unwrap();
In the Login component, I successfully receive and update the AppState, and I can see the updated state in the console log. However, after the redirection to the home page (/), the AppState is reset, and the user information is lost.
The context is passed using ContextProvider, but it seems that the state doesn't persist when switching routes.
I would really appreciate some assistance with this issue. Why is the state not persisting after the page is redirected? How can I ensure that the AppState remains consistent across different routes?
Thank you for your help!
this is the code:
/app.rs
#[derive(PartialEq,Debug)]
pub struct AppState {
pub user: Option,
}
impl AppState{
pub fn new() -> Self {
Self {
user: None,
}
}
pub fn is_login(&self) -> bool {
self.user.is_some()
}
}
pub type AppStateContext = Rc<RefCell>;
#[derive(Clone, Routable, PartialEq)]
pub enum Route {
#[at("/")]
Home,
#[at("/login")]
Login,
#[at("/register")]
Register,
#[at("/404")]
NotFound,
}
fn switch(routes: Route) -> Html {
match routes {
Route::Home => html! { },
Route::Login => html! { },
Route::Register => html! { },
Route::NotFound => html! { },
}
}
#[function_component(App)]
pub fn app() -> Html {
let app_state = Rc::new(RefCell::new(AppState::new()));
}
//login.rs
#[derive(Serialize, Deserialize, Clone)]
pub struct UserLogin {
pub username: String,
pub password: String,
}
#[derive(Properties,PartialEq)]
pub struct LoginProps{
pub app_state: AppStateContext,
}
#[function_component(Login)]
pub fn login() -> Html {
let app_state = use_context::().expect("no context found");
}
Beta Was this translation helpful? Give feedback.
All reactions