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.