I was trying to use Next dynamic route fetching API to get data for my pages dynamically but always getting 404 error on my fetch. What am I doing wrong?
The page is working fine with dynamic routes, but the fetch does not recognize the path to reach the "[pages].js" file.
Page: app/application/[page]/[tab]
Api Fetch: app/api/gantt/[page].js
my client side is: (app/application/[page]/[tab]/page.js)
"use client";
import { useEffect, useState } from "react";
const Page = ({ params }) => {
const { page, tab } = params;
const [data, setData] = useState(null);
useEffect(() => {
fetch("http://localhost:3000/api/gantt/" + page, {
method: "GET",
cache: "no-store",
}).then((data) => setData(data));
}, []);
console.log("data: ", data);
return <h1>APPLICATION/[PAGE]/[TAB] PAGE</h1>;
};
export default Page;
fetch handler:
export default function handler(req, res) {
const { page } = req.query;
console.log("page: ", page);
res.status(200).json({ page: page });
}
I get this error: "GET [path] 404 (Not Found)"
2
Answers
I found the solution, I was trying to do it the old way, but I'm using the next app router (13.4), so I need to use route handlers, just create the hierarchy of pages "api/gantt/[page]/route.js". So it get there:
You need to use
useEffect
with thevariables
will be changed.So you can change your
useEffect
like this.If the 2nd parameter of
useEffect
is[]
, the 1st parameter – arrow function is executed only once when the component initialized.But it is like
[variable]
, it is executed every change that variable.thank you.