use_router_internal.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. use dioxus::prelude::{ScopeId, ScopeState};
  2. use crate::{contexts::router::GenericRouterContext, prelude::*};
  3. /// A private hook to subscribe to the router.
  4. ///
  5. /// Used to reduce redundancy within other components/hooks. Safe to call multiple times for a
  6. /// single component, but not recommended. Multiple subscriptions will be discarded.
  7. ///
  8. /// # Return values
  9. /// - [`None`], when the current component isn't a descendant of a [`GenericRouter`] component.
  10. /// - Otherwise [`Some`].
  11. pub(crate) fn use_router_internal<R: Routable>(
  12. cx: &ScopeState,
  13. ) -> &Option<GenericRouterContext<R>> {
  14. let inner = cx.use_hook(|| {
  15. let router = cx.consume_context::<GenericRouterContext<R>>()?;
  16. let id = cx.scope_id();
  17. router.subscribe(id);
  18. Some(Subscription { router, id })
  19. });
  20. cx.use_hook(|| inner.as_ref().map(|s| s.router.clone()))
  21. }
  22. struct Subscription<R: Routable> {
  23. router: GenericRouterContext<R>,
  24. id: ScopeId,
  25. }
  26. impl<R: Routable> Drop for Subscription<R> {
  27. fn drop(&mut self) {
  28. self.router.unsubscribe(self.id);
  29. }
  30. }