I’m new to Next.js and server-side rendering, and I’m trying to get the individual slug for each job that I have posted. I am using the app router
and have set up the following page: src/app/Job/[slug]/page.js
Here’s the code:
async function getJobById(slug) {
const response = await fetch(`http://localhost:3000/api/Job/${slug}`, {
method: "GET",
});
return response.json();
}
export default async function JobId({ params }) {
const { slug } = await getJobById(params.slug);
return (
<>
<h1>{slug.pay}</h1>
<h1>{slug.aboutCompany}</h1>
<h1>{slug.experience}</h1>
etc...
</>
);
}
I have several jobs posted, but when I attempt to click on one using this link located in the jobsCard.js component
<Link href={/Job/${slug}}>View job</Link>
, I encounter numerous errors. Trying different solutions.
For reference heres the jobs api which is getting the list of jobs
import { useState, useMemo, useEffect } from "react";
import JobsCard from "./jobsCard.js";
const Jobs = () => {
const [jobmaps, setJobs] = useState([]);
useEffect(() => {
async function fetchJobsCard() {
try {
const response = await fetch("/api");
const data = await response.json();
if (!response.ok) {
throw new Error("Somethung went wrong");
}
setJobs(data);
} catch (error) {
console.log(error);
}
}
fetchJobsCard();
}, []);
return (
<Container maxW={"6xl"}>
{jobmaps.map((job, index) => (
<JobsCard
key={index}
companyName={job.companyName}
country={job.country}
setting={job.setting}
role={job.jobTitle}
elevatorPitch={job.aboutCompany}
experience={job.experience}
pay={job.pay}
/>
))}
</Container>
);
};
export default Jobs;
edit adding my api/route.js
import { MongoClient } from "mongodb";
import { NextResponse } from "next/server";
export async function POST(req) {
try {
const chunks = [];
for await (const chunk of req.body) {
chunks.push(chunk);
}
const body = Buffer.concat(chunks).toString();
const data = JSON.parse(body);
const client = await MongoClient.connect(
"mongodb+srv://username:[email protected]/jobupload?retryWrites=true&w=majority&appName=Cluster0"
);
const db = client.db();
const propertyCollections = db.collection("jobs");
const result = await propertyCollections.insertOne(data);
console.log(result);
client.close();
return NextResponse.json({ message: "job uploaded" });
} catch (error) {
return NextResponse.json(
{ error: "Failed to upload job" },
{ status: 500 }
);
}
}
export async function GET(request) {
const client = await MongoClient.connect(
"mongodb+srv://username:[email protected]/jobupload?retryWrites=true&w=majority&appName=Cluster0"
);
const db = client.db();
const propertyCollections = db.collection("jobs");
const result = await propertyCollections.find().toArray();
client.close();
return NextResponse.json(result);
}
2
Answers
You are passing
params.id
togetJobById()
but you set your dynamic route to use[slug]
in your case you should useparams.slug
, check the example provided in nextjs docs.If you wanna use
id
you can change your folder name tojob/[id]/page.js
or even
[jobId]
and make sure you are using the correct name in your params (params.jobId
orparams.id
depending on your folder name)I think that if your folder structure is
src/app/Job/[slug]/page.js
then you have to access theslug
.So your code should have been: