Utilizing the useRouter
hook in my current project.
Incorporating templated pages throughout the application.
Implementing a useEffect
hook that responds to changes in the router
and makes an API call.
Attempting to forward the entire URL to /api/${path}.json${query}
const u = new URL(`https://example.com${router.asPath}`)
const path = `/api${u.pathname}.json${u.search}`
Encountering an issue where the router appears to fire twice, once with the template and then again with parameters like:
/[design]/[product]
/blue/shirt
This results in the API call being triggered twice.
Below is the code snippet for my hook:
export const usePage = () => {
const router = useRouter();
const [page, setPage] = useState()
useEffect(() => {
(async () => {
// extracting query from next.js params
const u = new URL(`https://example.com${router.asPath}`)
const path = `/api${u.pathname}.json${u.search}`
console.log({ path })
const results = await fetch(path, { method: 'GET' });
const json = await results.json();
setPage(json)
})();
}, [router]);
return page;
}
Considering implementing a conditional check within the hook to detect [|]
in the URL before running the API call. Would appreciate any alternative suggestions or solutions.