2021-09-12 09:54:47 +00:00
|
|
|
use crate::infra::{api::HostService, cookies::delete_cookie};
|
2021-05-23 15:07:02 +00:00
|
|
|
use anyhow::Result;
|
2021-05-18 17:04:06 +00:00
|
|
|
use yew::prelude::*;
|
2021-05-23 15:07:02 +00:00
|
|
|
use yew::services::{fetch::FetchTask, ConsoleService};
|
2021-05-18 17:04:06 +00:00
|
|
|
|
|
|
|
pub struct LogoutButton {
|
|
|
|
link: ComponentLink<Self>,
|
|
|
|
on_logged_out: Callback<()>,
|
2021-05-23 15:07:02 +00:00
|
|
|
// Used to keep the request alive long enough.
|
|
|
|
_task: Option<FetchTask>,
|
2021-05-18 17:04:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, PartialEq, Properties)]
|
|
|
|
pub struct Props {
|
|
|
|
pub on_logged_out: Callback<()>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub enum Msg {
|
2021-05-23 15:07:02 +00:00
|
|
|
LogoutRequested,
|
|
|
|
LogoutCompleted(Result<()>),
|
2021-05-18 17:04:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Component for LogoutButton {
|
|
|
|
type Message = Msg;
|
|
|
|
type Properties = Props;
|
|
|
|
|
|
|
|
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
|
|
|
|
LogoutButton {
|
2021-05-30 15:07:34 +00:00
|
|
|
link,
|
2021-05-18 17:04:06 +00:00
|
|
|
on_logged_out: props.on_logged_out,
|
2021-05-23 15:07:02 +00:00
|
|
|
_task: None,
|
2021-05-18 17:04:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn update(&mut self, msg: Self::Message) -> ShouldRender {
|
|
|
|
match msg {
|
2021-05-23 15:07:02 +00:00
|
|
|
Msg::LogoutRequested => {
|
|
|
|
match HostService::logout(self.link.callback(Msg::LogoutCompleted)) {
|
|
|
|
Ok(task) => self._task = Some(task),
|
|
|
|
Err(e) => ConsoleService::error(&e.to_string()),
|
|
|
|
};
|
|
|
|
false
|
|
|
|
}
|
|
|
|
Msg::LogoutCompleted(res) => {
|
|
|
|
if let Err(e) = res {
|
2021-05-18 17:04:06 +00:00
|
|
|
ConsoleService::error(&e.to_string());
|
|
|
|
}
|
2021-05-23 15:07:02 +00:00
|
|
|
match delete_cookie("user_id") {
|
|
|
|
Err(e) => {
|
|
|
|
ConsoleService::error(&e.to_string());
|
|
|
|
false
|
|
|
|
}
|
|
|
|
Ok(()) => {
|
|
|
|
self.on_logged_out.emit(());
|
|
|
|
true
|
|
|
|
}
|
2021-05-18 17:04:06 +00:00
|
|
|
}
|
2021-05-23 15:07:02 +00:00
|
|
|
}
|
2021-05-18 17:04:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn change(&mut self, _: Self::Properties) -> ShouldRender {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
|
|
|
fn view(&self) -> Html {
|
|
|
|
html! {
|
2021-09-19 17:44:53 +00:00
|
|
|
<button
|
|
|
|
class="btn btn-primary"
|
|
|
|
onclick=self.link.callback(|_| Msg::LogoutRequested)>
|
|
|
|
{"Logout"}
|
|
|
|
</button>
|
2021-05-18 17:04:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|