Template URI parameters are being used in a router call

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:

  1. /[design]/[product]
  2. /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.

Answer №1

Temporary fix: 😭

const fetchPageData = async () => {
    try {
        const response = await fetch('/api/page-data.json');
        const jsonData = await response.json();
        setPage(jsonData);
    } catch (error) {
        console.error('Error fetching page data:', error);
    }
}

export const usePage = () => {
    const router = useRouter();
    const [page, setPage] = useState();

    useEffect(() => {
        if (!router.asPath.includes('[')) {
            fetchPageData();
        }
    }, [router]);

    return page;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pause before sending each request

How can we optimize the Async Validator so that it only sends a request to JSON once, instead of every time a letter is typed in the Email form? isEmailExist(): AsyncValidatorFn { return (control: AbstractControl): Observable<any> => { ...

Unable to retrieve attributes for the upcoming image

I've been working with Next.js and using next/image for displaying images. However, I'm facing an issue where the CSS is not being applied correctly within it. The image is in SVG format and has been placed in the public folder. To style it, I am ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Retrieving Information from the Nextjs13 Server Component

Currently, I am developing a web application using NextJS along with MongoDB which is handled through Mongoose. Here is an overview of my Server Component: import { getPosts } from "@/lib/mongoDb/post"; import PostsClientComponent from "./PostsClien ...

In React (Next.js), the act of replacing a file is performed instead of adding a file

I kindly request a review of my code prior to making any changes. const test = () => { const [files, setFiles] = useState ([]); //I believe I need to modify the following statement. const handleFile = (e) => { const newFiles = [] for (let i= ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Building a secure, highly nested object in Prisma

I am currently utilizing a data structure in Prisma and Nextjs that includes authentication via Next-Auth. The structure is as follows: user |-->profile |-->log |-->sublog At the moment, CRUD operations are being sent to the datab ...

Issue with CORS on Next.js static files leading to broken links on version 10.1.4

Currently, my Nextjs application is fetching its static files from Cloudfront. During deployment, I upload the /static folder to S3. After updating to version 9, I encountered a strange problem where some of my CSS files are triggering a CORS error: Acces ...

How can you inject the parent component into a directive in Angular 2, but only if it actually exists?

I have developed a select-all feature for my custom table component. I want to offer users of my directive two different ways to instantiate it: 1: <my-custom-table> <input type="checkbox" my-select-all-directive/> </my-custom-table> ...

Issue Confirming Signature - New Version of Next.JS with Stripe Integration

Having trouble verifying the request signature in my Stripe webhook endpoint. I keep encountering this error: No signatures found matching the expected signature for payload. Have you passed the raw request body received from Stripe? I've experimente ...

Using Next.js and ReactGA for Google Analytics integration

Hey there, I've integrated ReactGA4 to track my Analytics in my Next.js app. However, I'm experiencing an issue where I am unable to see the path of the user until they reload the page. Here is a snippet of my code: ReactGA.initialize("UA-xx ...

Dynamic Angular component loading with lazy loading

In my Angular 4.1.3 project, I am currently developing a mapping application that incorporates lazy-loading for various tool modules. At present, the tools are loaded within the map using a router-outlet. However, I now need to expand this functionality to ...

Encountering issues with deploying an Angular 8 website using a specific configuration

My current project is built on Angular 8, and I am in the process of publishing it locally before deploying it. When running the build step, I specify an environment name called internalprod: src ├───app ├───environments │ environme ...

Understanding how to incorporate third party HTML tags into your React project

Is there a method to incorporate appearing animations using the useInView hook? The obstacle I am facing is that the necessary tag is not present in my code; instead, it is retrieved as a single tag from a third party Ghost through dangerouslySetInnerHTML. ...

React and Next.js bug: retrieving the value from the previous page's session storage

Within my React and Next.js application, I'm working on including a back button feature. To achieve this, I have introduced the use of currentPath and prevPath stored in the session storage within the _app.js file. // pages/_app.js function MyApp({ Co ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

Why is the source alignment different when using Next.js compared to WordPress?

As a newcomer to NextJS, I am eager to learn more about it in order to develop websites that are easily discoverable by Google's search engine algorithms and have strong SEO performance. Wordpress is renowned for its SEO capabilities as it neatly outp ...

Sharing state between two functions in React using Hooks

Coming from a background in Vue, I am struggling to comprehend how to conditionally show something when the HTML is fragmented into different parts. Imagine having this structure: import React, { useState } from "react"; const [mobileNavOpen, setMobi ...

Is it acceptable to include a @types library as a regular dependency in the package.json file of a Typescript library?

Should the library also be compatible with Typescript projects? I am developing a Typescript library that utilizes node-fetch and @types/node-fetch, which will be shared through an internal NPM registry within the company. If I only include @types/node-f ...