Encountering an error when accessing dynamically routed pages in Next JS

When I click on a link within the web app to navigate to a dynamically routed page for a product (http://localhost/1), everything works as intended.

However, if I manually input a specific product number in the search bar to navigate directly to that page (http://localhost/2), I encounter the following error:

Server Error
TypeError: Cannot read property 'image' of undefined 

> | <Image src={"/../public/images/" + p.image}
                                        ^

I have attempted to ensure that the types match and have thoroughly reviewed the Next JS documentation on dynamic routing.

I even tried removing the array zero from the filter, but the issue persists without resolution.

I am now considering whether the routing only functions correctly when clicking on a link within Next JS. Could there be a missing setting or configuration that I have overlooked?

pages/[pid].js

import { useRouter } from 'next/router'
import Image from 'next/image'

import data from '../products.json'

export default function Template() {
  const router = useRouter()
  const { pid } = router.query

  const p = data.filter(product => product._id == pid)[0]  // Choose one result

  return (
    <Image src={"/../public/images/" + p.image}
           height="500px"
           width="500px" />
  )
}

products.json

[
  {
    "_id": 1,
    "name": "Toyota",
    "image": "toyota.png"
  },
  {
    "_id": 2,
    "name": "BMW",
    "image": "bmw.png"
  }
]

Update: After attempting to hardcode the src attribute in the Image tag, I received a new error pointing to other references as the issue. It appears that the problem lies in not receiving an object when calling the data object.

Answer №1

Hurray! I finally resolved the issue at hand!

Simply using Dynamic Routes with the 'useRouter()' function was not sufficient. I also needed to implement these two essential functions:

export async function getStaticProps(context) {
  // A placeholder function calls getStaticProps for getStaticPaths.
  return { props: {} }
}

export async function getStaticPaths() {
  const dynamicFiles = products.map(product => (
    {
      params: { pid: String(product._id) },  // Product IDs are integers in JSON file
    }
  ))

  return {
    paths: dynamicFiles,
    fallback: false
  }
}

This approach is logical as it prevents unauthorized path access by users. For instance, a user would not be able to manipulate http://localhost/1234 when 1234 is an invalid parameter.

Discover more about implementing getStaticProps in dynamic routes on Next.js documentation

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 is the reason behind the non-exportation of actions in Redux Toolkit for ReactJS?

Currently, I am utilizing @reduxjs/toolkit along with reactjs to create a shopping cart feature. However, I am encountering an issue when attempting to export actions from Cart.js and import them into other files like cart.jsx and header.jsx. The error mes ...

Having trouble integrating NEXT AUTH with Firebase due to an error: "Cannot import statement outside

Let's take a look at our firebase configuration file: import { getFirestore } from "firebase/firestore"; export const firebaseConfig = { apiKey: process.env.FIREBASE_API_KEY, authDomain: process.env.FIREBASE_AUTH_DOMAIN, projectId: pr ...

The system displayed an 'Error' stating that the variable 'index' is defined in the code but is never actually utilized, resulting in the (no-unused-vars) warning

I have configured eslint and eslint-plugin-react for my project. Upon running ESLint, I am encountering no-unused-vars errors for every React component in the codebase. It seems like ESLint is not properly identifying JSX or React syntax. Any suggestions ...

Presenting a ui-router modal while maintaining the parent state's refresh-free appearance

I have implemented a unique feature in my angular app called modalStateProvider. It allows me to easily have modals with their own URLs. // Implementing the modalStateProvider app.provider('modalState', [ '$stateProvider', function ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Complete interaction with child processes in Node.js

I have a basic C++ program compiled using the command gcc 1.cpp -o 1.exe. // 1.cpp #include <stdio.h> int main(){ int num = 0; scanf("%d", &num); printf("%d", num + 1000); scanf("%d", &num); printf("\n%d", num + 1000); ...

The styling in NextJs/Material-ui does not function properly with makeStyles CSS

Currently, I am creating my personal website with NextJS and Material-UI in the front-end and Strapi in the back-end. However, I have encountered an issue where the CSS written under the const 'useStyles=makeStyles' is not consistently applied wh ...

Issue encountered while trying to exhibit jpg image content from server side on html

I am attempting to display an image from server-side data using an Ajax call. The data stored on the server looks something like this: "ÿØÿàJFIFÿÛC4­¶¸UOHlʵcBò)3¹_È'I4~&éüÿ§Ú<ã©ã4>'Øù¿ÇÄmËCÈgÚsZ¥ë" Upo ...

Transmitting information via the Link tag in Next.js

I am utilizing Link tags in next js to pass state data to the redirected page. Upon redirection from the home page to the course page, I include courseData in the state. <Link href={{pathname: '/course', state: {courseData}}}> <a> ...

JavaScript and CSS tabs with smooth transition effect

I want to create tabs that smoothly fade between each other when switching. The code I have works, but there's a slight issue. When transitioning from one tab to the previous one, there is a momentary glitch where the last tab briefly changes state be ...

Discover a method to retrieve all recommended strings based on a search query using JavaScript

I have two strings: one containing all the values of countries and the second string that I entered when searching for a country. Now, I am looking to retrieve all results that contain "In", such as India and Indonesia. For example, if I search for "IN" ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

The function to navigate, 'navTo', is not defined and so it cannot be read

I am trying to create a navigation button in my SAPUI5 application deployed on Fiori _onPageNavButtonPress: function () { var oHistory = History.getInstance(); var sPreviousHash = oHistory.getPreviousHash(); if (sPreviousHash !== ...

How to access the dynamic route's path in Next.js when using Server Components?

Obtaining the dynamic route path in a Next JS server component poses a challenge. This task is simple when working with client components. If you are working on src/app/[id]/page.tsx "use client"; import { usePathname } from "next/navigatio ...

Issues with retrieving data from Firestore and storing it into an array in a React

Struggling to fetch data from my firestore and display it on the webpage. Despite trying all possible solutions and searching extensively, I am unable to get it working. When using the code below, nothing appears on the website. However, if I switch to th ...

What is the best way to implement conditional rendering for the next/image component in a React project?

I am facing a challenge with my library that is being utilized across various websites. One of these websites is built on Next JS, and I am looking to implement the next/image component for all images on this particular site without impacting the functio ...

Entering a new row and sending information through ajax

I'm looking for some help with a web page I have that includes a particular table structure: **Check out my Table*:* <table id="staff" class="table"> <thead> <tr> <th>First Name</th> <th>Last Nam ...

Ensuring the presence of a bootstrap angular alert with protractor and cucumberJS

I am currently utilizing protractor, cucumberJS, and chai-as-promised for testing. There is a message (bootstrap alert of angularJS) that displays in the DOM when a specific button is clicked. This message disappears from the DOM after 6000 milliseconds. ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

The jQuery script automatically triggers submission on its own

Does anyone have an idea why the form auto-submits itself? I can't figure out why it's doing that. I'm using query parsley to validate the form in a modal. When a user opens the modal and starts typing in the text area, they must type at l ...