Search code examples
next.jsdynamic-routing

Get undefined while try to create a dynamic route in nextjs


I am creating a blog with next.js typescript and I succeeded to fetch all my posts from MongoDB. But I couldn't create the single page which shows a single post using the id.

This is my route.ts

I tested the API and it works correctly I just put it here in case of clarification.

import { connectDB } from "@/database/dbConfig";
import Post from "@/models/postModel";

// GET /api/posts
export const GET = async ({ params }) => {
  try {
    await connectDB();

    const post = await Post.findById(params.id);

    if (!post) return new Response("Property Not Found", { status: 404 });
    return new Response(JSON.stringify(post), {
      status: 200,
    });
  } catch (error) {
    console.log(error);
    return new Response("Something went wrong", { status: 500 });
  }
};

Now this is the the singlePostPage component:


const SinglePostPage = () => {
  const { id } = useParams();
  const [singlePost, setSinglePost] = useState();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchPosts = async () => {
      if (!id) return;
      try {
        const singlePost = await fetchSinglePost(id);
        setSinglePost(singlePost);
      } catch (error) {
        console.error("Error fetching posts" + error);
      } finally {
        setLoading(false);
      }
    };

    if (singlePost === null) {
      fetchPosts();
    }

  }, [id, singlePost]);

  return (
    <div className="singlepostPage">
      <h2>Test</h2>
    </div>
  );
};

export default SinglePostPage;

And this is the fetchSinglePost function:

async function fetchSinglePost(id: string | any) {
  try {
    if (!apiDomain) {
      return null;
    }

    const res = await fetch(`${apiDomain}/posts/${id}`);

    if (!res.ok) {
      throw new Error("Failed to fetch data");
    }

    return await res.json();
  } catch (error) {
    throw new Error("Failed to fetch data");
  }
}

I get undefined when I console.log the singlePost. Last time I was trying I got null. I did it with Nextjs javascript version before and it worked.
I've already checked the apiDomain in .env and it's correct.


Solution

  • in the MongoDB one document finding you use the findOne method. here you are using findById. I think you missed this. const post = await Post.findOne(query, options); not const post = await Post.findById(params.id);