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

Unit test for Storybook add-on is failing due to NextJS useRouter() returning null

I've encountered an issue while trying to integrate my stories into unit tests using Jest and React Testing Library in a NextJS application. When viewing the components in Storybook, everything works smoothly with the Storybook Addon Next Router. Howe ...

What is the best way to ensure a query string URL is functional when accessed directly in next.js?

On my next.js website, I have implemented a search bar where users can input queries such as "delhi" and hit the submit button to trigger an API call. The API call is made to http://localhost:3000/jobs/job-search/related-jobs?title=%20delhi which should di ...

Creating a TypeScript NPM package that provides JSX property suggestions and autocomplete functionality for Intellisense

I developed a compact UI toolkit and released it on the NPM registry. The library is built using strongly typed styled-components (TypeScript) and can be easily integrated into React applications. It functions perfectly after installation with npm install ...

Guide on using automapper in typescript to map a complex object to a "Map" or "Record" interface

I have been utilizing the automapper-ts with typescript plugin for automatic mapping. Check it out here While it works smoothly for simple objects, I encountered issues when dealing with complex ones like: Record<string, any> or Map<string, Anoth ...

Is it possible to swap out the Firestore module `doc` with the `document` module

I enjoy using the Firebase version 9 modules, however, I find that doc is not to my liking. It would be better if it were document, similar to how collection is not shortened to col. The following code does not function as expected: import { doc, collecti ...

Is it not possible to utilize inline "if" statements in conjunction with useEffect within a functional React component?

I'm currently working on integrating Okta's React SDK into a TypeScript-based application using functional components instead of class-based ones. My main challenge lies in rendering a part of the app's menu based on the user's authenti ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Guide to integrating a GitHub Gist into a NextJS app

I'm currently working on a static website using NextJS and I'm looking to incorporate Github Gist into it. I've experimented with various npm packages designed for React, but they seem to rely on browser features that aren't available w ...

Top method for integrating Chat functionality with WebSockets in NextJS version 13

I am working on a NextJS 13 application with a app-router backend and using MongoDB as my database. My task is to incorporate a real-time chat feature into the app where multiple chats of a single user can run simultaneously, requiring separate web-socket ...

How to implement ngx-spinner in an Angular http subscribe operation

I'm trying to incorporate a spinner into my Angular Application using ngx-spinner. I've come across this library but haven't found enough practical examples on how to use it effectively. Specifically, I want to integrate the spinner with my ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

Issue: Button ClickEvent is not triggered when the textArea is in onFocus mode

Is there a way to automatically activate a button ClickEvent when the textArea input is focused? Keep in mind that my textArea has some styles applied, causing it to expand when clicked. Here is an example: https://stackblitz.com/edit/angular-ivy-zy9sqj?f ...

Combining Typescript Declarations for Express Request Object with Passport.js User/Session Integration

In my express/nodejs app, I am encountering issues with properties on the request.user object even after implementing Declaration Merging for authentication using passportjs middleware. To address this, I created a file at /types/index.d.ts in the project ...

How can I set the width of a container dynamically using the Next JS Image component?

I have a situation where I am trying to set the height of an image within a container div to be equal to 100% of the container's height, while allowing the width of the container to adjust based on the image's aspect ratio. When using a standard ...

Error: The function `map` cannot be applied to `cardsData`

I'm encountering an issue where I need to store user queries in cardsData and then map through the data within cardsData. However, when I run the code on my terminal, it throws an error. As a beginner, I've researched various forums that mention ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

Exploring the World of Popper.js Modifiers

Within our React and Typescript application, we integrate the react-datepicker library, which utilizes popper.js. Attempting to configure PopperModifiers according to the example provided here: . Despite replicating the exact setup from the example, a typ ...

nextAuth.js is failing to access the accessToken, returning only the values {iat, exp, jti} instead

Here is the code I am working with: import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" export default NextAuth({ sectret:process.env.NEXTAUTH_SECRET, session: { strategy: "jw ...

What is the best way to implement smooth scrolling to an anchor tag from a different page in NextJS?

In my NextJS project, I have two main pages - the Home page and the Leaderboard page. The navigation bar code looks like this: <div className={styles.navItem}> <Link href="/"> <a className={styles.navLinks} onClic ...

Encountering an issue with setting up MikroORM with PostgreSQL due to a type

I'm currently working on setting up MikroORM with PostgreSQL, but I've encountered a strange error related to the type: Here is the code snippet: import { MikroORM, Options} from "@mikro-orm/core"; import { _prod_ } from "./consta ...