I’m trying to fetch posts from my Strapi backend in a Next.js application. My Strapi server is running on localhost:1337. Here is my component code:
When I try to fetch data, posts is logged as undefined
I have confirmed that NEXT_PUBLIC_API_URL is correctly set to http://localhost:1337 in my .env file.
import React from "react";
import Post from "./Post";
const RecentPosts = ({ posts }) => {
console.log(posts); // Logs 'undefined'
return (
<div className="mx-auto flex h-full w-full max-w-7xl flex-col gap-12 p-4 md:p-8">
<div className="rounded-lg bg-backgroundSecondary p-4">
<h2 className="text-balance text-center text-3xl font-semibold uppercase text-[#f2f2f2] md:text-left md:text-4xl lg:text-5xl xl:text-6xl">
Ostatnie wpisy
</h2>
<p className="text-center text-lg md:text-left">
Zobacz kilka z naszych ostatnich wpisów i dowiedz się więcej na temat
Arbosfery!
</p>
</div>
<div className="flex flex-col gap-6 xl:flex-row">
</div>
</div>
);
};
RecentPosts.getInitialProps = async () => {
try {
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
const res = await fetch(`${apiUrl}/posts?_sort=createdAt:desc`);
if (!res.ok) {
throw new Error("Failed to fetch data");
}
const posts = await res.json();
return { posts };
} catch (error) {
console.error("Error fetching data:", error);
return { posts: [] };
}
};
export default RecentPosts;```
Why is posts undefined when it should contain the fetched data from the API?