Skip to content

Commit

Permalink
fix(usePathname): prevent duplication of subpath in pathname (#1333)
Browse files Browse the repository at this point in the history
  • Loading branch information
vgeorge authored Dec 17, 2024
2 parents 55c04c3 + 5c0bbbb commit 9637f97
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 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 @@ -13,14 +28,16 @@ import { useEffect, useState } from 'react';
*/
export const usePathname = () => {
const [pathname, setPathname] = useState(
typeof window !== 'undefined' ? window.location.pathname : ''
typeof window !== 'undefined'
? window.location.pathname.replace(appPathname, '')
: ''
);

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

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

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

0 comments on commit 9637f97

Please sign in to comment.