use crate::QueryError;
#[derive(Debug, Clone, Default)]
pub enum QueryState<T: Clone> {
#[default]
Idle,
Loading,
Refetching(T),
Success(T),
Stale(T),
Error {
error: QueryError,
stale_data: Option<T>,
},
}
impl<T: Clone> QueryState<T> {
pub fn is_idle(&self) -> bool {
matches!(self, Self::Idle)
}
pub fn is_loading(&self) -> bool {
matches!(self, Self::Loading)
}
pub fn is_fetching(&self) -> bool {
matches!(self, Self::Loading | Self::Refetching(_))
}
pub fn is_success(&self) -> bool {
matches!(self, Self::Success(_))
}
pub fn is_stale(&self) -> bool {
matches!(self, Self::Stale(_))
}
pub fn is_error(&self) -> bool {
matches!(self, Self::Error { .. })
}
pub fn data(&self) -> Option<&T> {
match self {
Self::Success(d) | Self::Stale(d) | Self::Refetching(d) => Some(d),
Self::Error { stale_data, .. } => stale_data.as_ref(),
_ => None,
}
}
pub fn error(&self) -> Option<&QueryError> {
match self {
Self::Error { error, .. } => Some(error),
_ => None,
}
}
pub fn unwrap_or_default(&self) -> T
where
T: Default,
{
self.data().cloned().unwrap_or_default()
}
}