Skip to content

Commit

Permalink
fix(usePathname): extract app pathname when PUBLIC_URL is a full URL
Browse files Browse the repository at this point in the history
  • Loading branch information
vgeorge committed Dec 17, 2024
1 parent b1a13af commit 5c0bbbb
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions app/scripts/utils/use-pathname.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { useEffect, useState } from 'react';

const appPathname = (() => {
try {
const publicUrl = process.env.PUBLIC_URL;
if (!publicUrl || typeof publicUrl !== 'string') return '';

// Use base URL fallback
const url = new URL(publicUrl, window.location.origin);

// Remove trailing slash if present
return url.pathname.replace(/\/$/, '');
} catch {
return '';
}
})();

/**
* usePathname
* *
Expand All @@ -14,17 +29,15 @@ import { useEffect, useState } from 'react';
export const usePathname = () => {
const [pathname, setPathname] = useState(
typeof window !== 'undefined'
? window.location.pathname.replace(process.env.PUBLIC_URL ?? '', '')
? window.location.pathname.replace(appPathname, '')
: ''
);

useEffect(() => {
if (typeof window === 'undefined') return;

const updatePathname = () => {
setPathname(
window.location.pathname.replace(process.env.PUBLIC_URL ?? '', '')
);
setPathname(window.location.pathname.replace(appPathname, ''));
};

// Listen to popstate events (back/forward navigation)
Expand Down

0 comments on commit 5c0bbbb

Please sign in to comment.