skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    import { NextResponse } from "next/server";
    
    export const GET = async (req, params) => {
      /*
      params is {page: [page name]}
      */
    };
    
    

  2. You need to use useEffect with the variables will be changed.
    So you can change your useEffect like this.

    useEffect(() => {
      fetch("http://localhost:3000/api/gantt/" + page, {
        method: "GET",
        cache: "no-store",
      }).then((data) => setData(data));
    }, [page]);

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search