From c5f43dd13eefd1d42721952072a52a3bd0709dea Mon Sep 17 00:00:00 2001 From: Marc Espin Date: Tue, 28 Jan 2025 19:52:48 +0100 Subject: [PATCH] feat: Allow using `NavigationTarget` outside router (#3633) * feat: Allow using `NavigationTarget` outside of router * chore: Update import * chore: Update imports * fmt --- packages/router/src/hooks/use_router.rs | 6 ++++++ packages/router/src/navigation.rs | 24 +++++++++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/router/src/hooks/use_router.rs b/packages/router/src/hooks/use_router.rs index 5afea5cccb..b78c0f9e58 100644 --- a/packages/router/src/hooks/use_router.rs +++ b/packages/router/src/hooks/use_router.rs @@ -12,3 +12,9 @@ pub fn use_router() -> RouterContext { pub fn router() -> RouterContext { dioxus_lib::prelude::consume_context() } + +/// Try to acquire the router without subscribing to updates. +#[doc(alias = "url")] +pub fn try_router() -> Option { + dioxus_lib::prelude::try_consume_context() +} diff --git a/packages/router/src/navigation.rs b/packages/router/src/navigation.rs index 0c78c42b8b..cd331122fb 100644 --- a/packages/router/src/navigation.rs +++ b/packages/router/src/navigation.rs @@ -7,7 +7,9 @@ use std::{ use url::{ParseError, Url}; -use crate::{components::child_router::consume_child_route_mapping, routable::Routable, router}; +use crate::{ + components::child_router::consume_child_route_mapping, hooks::try_router, routable::Routable, +}; impl From for NavigationTarget { fn from(value: R) -> Self { @@ -94,20 +96,24 @@ impl From for NavigationTarget { impl From<&str> for NavigationTarget { fn from(value: &str) -> Self { - let router = router(); - match router.internal_route(value) { - true => NavigationTarget::Internal(value.to_string()), - false => NavigationTarget::External(value.to_string()), + match try_router() { + Some(router) => match router.internal_route(value) { + true => NavigationTarget::Internal(value.to_string()), + false => NavigationTarget::External(value.to_string()), + }, + None => NavigationTarget::External(value.to_string()), } } } impl From for NavigationTarget { fn from(value: String) -> Self { - let router = router(); - match router.internal_route(&value) { - true => NavigationTarget::Internal(value), - false => NavigationTarget::External(value), + match try_router() { + Some(router) => match router.internal_route(&value) { + true => NavigationTarget::Internal(value), + false => NavigationTarget::External(value), + }, + None => NavigationTarget::External(value.to_string()), } } }