Reputation: 33
I am working with Next.js 13, and I am trying to show a 404 page in a dynamic route when the id does not exist. This is my directory (I am using App Router):
/university/[id] -> page.tsx when I go to id 1 (exists) it shows the page with all the data, if I go to id 2 (does not exist) it shows the page without the data. Here I want to show the 404 page instead.
This is my code
import { useEffect, useState } from "react";
import { notFound } from "next/navigation";
import ProfileInfo from "@/components/ProfileInfo";
type UniversityProps = {
params: {
id: string;
};
};
const University = ({ params }: UniversityProps) => {
const [university, setUniversity] = useState({} as any);
const { id } = params;
useEffect(() => {
const fetchUniversity = async () => {
try {
const response = await fetch(`/api/profile/university/${id}`);
if (response.ok) {
const data = await response.json();
setUniversity(data);
} else {
notFound();
}
} catch (error) {
console.log(error);
}
};
if (id) fetchUniversity();
}, [id]);
return (
<>
<ProfileInfo />
<div className="py-8 max-w-7xl mx-auto">{university.name}</div>
</>
);
};
export default University;
I am trying to use notFound() from next/navigation but I get an error in the console. I also tried using return { notFound: true, }
Error: NEXT_NOT_FOUND
at notFound (webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/not-found.js:23:19)
at fetchUniversity (webpack-internal:///(app-pages-browser)/./app/(profile)/universidad/[id]/page.tsx:26:78)```
Upvotes: 0
Views: 349
Reputation: 33
I fixed by using useSWR instead of fetch
"use client";
import useSWR from "swr";
import { notFound } from "next/navigation";
import ProfileInfo from "@/components/ProfileInfo";
type UniversityProps = {
params: {
id: string;
};
};
const fetcher = (url: string) => fetch(url).then((res) => res.json());
const University = ({ params }: UniversityProps) => {
const {
data: university,
error,
isLoading,
} = useSWR<any>(`/api/profile/university/${params.id}`, fetcher);
if (error) {
notFound();
}
return (
<>
{!isLoading && (
<>
<ProfileInfo />
<div className="py-8 max-w-7xl mx-auto">{university.name}</div>
</>
)}
</>
);
};
export default University;
Upvotes: 0