I'm building a NextJS application and struggle to pass data into dynamically generated pages.
In my application, data is fetched from an Amazon S3 bucket and mapped. The fetch works as intended delivering a set of tiles populated with data from the external source.
{data
?.filter(
(item: any) =>
selectedCategory === null ||
item.videoCategory === selectedCategory
)
.map((item: any) => (
<div key={item.id}>
{showOverlay && (
<div className="relative inset-0 flex h-80 w-80 animate-pulse items-center justify-center bg-red-500 text-center"></div>
)}
<Link
href="/videos/normal/[video]"
as={`/videos/normal/${item.videoID}`}
>
<HoverVideoPlayer videoSrc={item.videoLink} />
</Link>
</div>
))}
Now, I want every tile to link to a dynamically generated detail page, for this I have generated a slugged [video].tsx page.
The data on each dynamically generated page should be based on the 'videoID' property of the data / array it was mapped from. The data looks like this:
"id": "2",
"videoLink": "https://media.w3.org/2010/05/sintel/trailer_hd.mp4",
"videoLinkDeep": "https://media.w3.org/2010/05/sintel/trailer_hd.mp4",
"videoTitle": "Stopmotion",
"videoID": "100007_LX",
Linking to the page works, the page component is rendered correctly, but as far as I can tell - no data whatsoever is passed.
My [video].tsx is setup like this:
import React from 'react';
const VideoPage = (props: {
params: VideoParams;
json: any;
video: any;
data: any;
}) => {
if (!props.video) {
return <p>Video not found</p>;
}
return (
<div>
<h1>{props.video.videoTitle}</h1>
</div>
);
};
interface VideoParams {
id: string;
}
export async function getServerSideProps({ params }: { params: VideoParams }) {
const res = await fetch('https://www.externalsource.com/VideoData.json');
const json = await res.json();
console.log(params.id);
console.log(json);
const video = json.find((item: any) => item.link === params.id);
console.log(video);
if (video) {
return {
props: {
video,
},
};
}
return {
props: {
video: null,
},
};
}
export default VideoPage;
I have checked all spelling / import related issues and integrated a Fallbacks and multiple console logs to debug:
This fallback is triggered: delivering a 'Video not Found' when opening one of the dynamic pages
if (!props.video) { return
Video not found
; }My console.log for the
console.log(video);
tells me that all data from the external source is fetched, but closes with an 'undefined'.
What is going wrong in the handover between the Link and the dynamic page?
CodePudding user response:
When you define a dynamic route in NextJS, the name of the file will be used as the param in params
. You're trying to access params.id
, but the file is named [video].tsx
, so you should be accessing params.video
.
Here's the documentation on dynamic routes: https://nextjs.org/docs/routing/dynamic-routes