Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]**

The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I want the name to appear in the route instead.

Let me walk you through how I approached this

Here are the interfaces representing the data structure

export type userFriends = {
  _id?: string;
  name?: string;
  perfil?: string;
  identifier?: string;
  notification?: boolean;
  friend?: boolean;
  createdAt?: string;
};

export type user = {
  _id?: string;
  name?: string;
  email?: string;
  password?: string;
  friends?: userFriends[];
  banner?: string;
  perfil?: string;
};

export interface IuserData {
  data: user;
}

export type multipleUsers = { data: user[] };

Now, let's take a look at the logic implemented

export const getStaticPaths: GetStaticPaths = async () => {
  const { data }: multipleUsers = await axios.get(
    "http://localhost:5000/api/user"
  );

  const paths = data.map(path => {
    return { params: { name: path.name, id: path._id } };
  });

  return { paths, fallback: true };
};

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const { data }: IuserData = await axios.get(
    `http://localhost:5000/api/user/singleU/${params.id}`
  );

  return {
    props: { data }
  };
};

The route only works when using [id] instead of [name], even though both parameters are included in the params object.

This consistently triggers an error in next.js

Error: Request failed with status code 500
    ...
   Error details here...
    ...

Any suggestions on what I can do to resolve this issue?

Appreciate your assistance!

Answer №1

getStaticPaths is a crucial function that helps populate the potential parameters for dynamic routes when generating a site statically. The params value passed to getStaticProps corresponds to the parameters defined in the route, with no hidden surprises.

An effective strategy involves memoizing user parameters so that getStaticProps can leverage previously fetched data during static site generation, rather than making redundant API calls:

const memoize = fn => {
  let promise, result;
  return () => {
    if (result) {
      return result;
    } else if (promise) {
      return promise;
    } else {
      promise = fn();
      try {
        result = await promise;
        return result;
      } finally {
        promise = null; // prevent memory leak
      }
    }
  }
}

const getUserLookup = memoize(async () => {
  const { data }: allUsers = await axios.get(
    "http://localhost:5000/api/user"
  );
  userIdLookup = new Map(
    data.map(({ _id, name}) => [name, _id])
  );
  return userIdLookup;
});

export const getStaticPaths: GetStaticPaths = async () => {
  const userNameIds = await getUserLookup();

  return {
    paths: [...userNameIds.entries()].map(([name, id]) => ({ name, id })),
    fallback: true
  };
};

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const lookup = await getUserLookup();
  const { data }: IuserData = await axios.get(
    `http://localhost:5000/api/user/singleU/${lookup.get(params.name)}`
  );

  return {
    props: { data }
  };
};

By ensuring that the static site building process occurs only once and within the same context, fetching users multiple times can be avoided.

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

What are some ways to optimize Ajax requests for improved speed when multiple identical requests are made on a single webpage?

When the webpage is loaded, a block is dynamically created using an Ajax call to retrieve data from another page. This structure is then populated and added to a specific DOM element. However, multiple Ajax calls during page loads are causing delays. Is ...

Retrieve the date for the chosen time slot by utilizing the fullCalendar feature

I've been experiencing issues with a piece of code that is supposed to retrieve the date corresponding to a user-selected slot. Here's what I've tried so far: $('.fc-agenda-axis.fc-widget-header').on('mousedown', functio ...

Next.js Role Control Automation: Step-by-Step Guide to Configuring Between Pages

view image description here Whenever there is a change in route information, the user's role information needs to be verified before accessing the desired page. If the user's role matches the permissions of the page, access should be granted an ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

The dynamic Vue.js transitions and effects are like a magic

I am using a v-for to render multiple child components: <div v-for="(pass) in scoringPass" :key="pass.decision"> <Pass :pass="pass"/> </div> Each of these child components contains a transition tag: &l ...

Is PHP-generated HTML not responding to external Javascript?

I have been attempting to create a form where, upon checking a checkbox, the onClick() event will enable a select option. Below is my PHP code: function generateOption() { for($x = 0; $x < 10; $x++) { echo "<option value='".$x."'> ...

Scrolling infinitely within the side menu using ion-infinite-scroll

I'm encountering an issue with using Ion-infinite-scroll within ion-side-menu, as the load more function is not being triggered. Is it permitted to utilize ion-infinite-scroll inside ion-side-menu? Although I have added the directive, the method "lo ...

The issue of empty req.body in POST middleware with Medusa.JS

Feeling completely frustrated with this issue. Grateful in advance to anyone who can lend a hand. Any insights on why req.body is showing up empty? Medusa.JS should be utilizing bodyParser by default, correct? It was functioning fine earlier today but now ...

Tips for making immutable state changes in React

Is there a way to update specific content in the state without affecting all other data stored in the state? Just to provide some context: The function below is executed within another "handleChange" function that takes the event as input and assigns the ...

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

Trouble with parsing JSON in rxjs ajax response

Currently, I am facing an issue while parsing a JSON string within an ajax callback in Angular2. After executing response.json()) and using console.log(), everything seems to be functioning correctly. This is the specific JSON data that I am attempting ...

Enhancing the theme using material-ui@next and typescript

While developing my theme using material-ui, I decided to introduce two new palette options that would offer a wider range of light and dark shades. To achieve this, I extended the Theme type with the necessary modifications: import {Theme} from "material ...

Struggling to Confirm Inaccuracies in Material UI Forms

Struggling to validate form errors in React with Material UI using JOI and running into issues. Even the console.log() results are not showing up in my validate function. The error display is also confusing. ... import React from "react"; import ...

When TypeScript tsc is unresponsive, there is no output or feedback provided

Just getting started with TypeScript! I've been working on transitioning my React.js project from JavaScript to TypeScript. I managed to resolve all the bugs and verified that it runs smoothly when using npm start. However, whenever I try to comp ...

Having trouble with jQuery variable assignments not working in Safari?

My jQuery 1.3.2 code is encountering issues with Safari 4 for reasons unknown to me. Even though all my javascript references are placed right before the closing <body> tag, I am facing difficulties with the following snippet: var status = $(' ...

Testing Angular 2 components with material icons and images

Recently, I finished creating a unique component that showcases an image, material icons, and a custom directive known as ticker. This directive allows for scrolling text if it exceeds the width of the element. https://i.stack.imgur.com/GpDSr.png My next ...

What is the reason behind the asynchronous nature of getStaticProps() in Next.js?

What is the reasoning behind getStaticProps() being designed as an asynchronous function in Next.js? My understanding is that an async function is moved off the main thread during execution to prevent it from blocking while running tasks that might take so ...

Clicking elements reveal but page height remains unchanged?

Clicking on a label within #row-product_id_page-0-0 triggers the display of #row- elements as shown in the code snippet below: $('#row-product_id_page-0-0 label').click(function() { var str = $(this).find('.am-product-title').text ...

An object resulting from the combination of two separate objects

After reading a helpful solution on StackOverflow about merging properties of JavaScript objects dynamically, I learned how to utilize the spread operator in Typescript. However, one question still remains unanswered - what will be the type of the object c ...

Navigating data in a Json array object

Can someone assist me in retrieving data from a JSON array file stored at the following link? Html <div> <div v-for="data in myJson.id " >{{ data }}</div> </div> js import json from '.././json/data.json&apo ...