I am working with Strapi and NextJS 14+ and I have successfully fetched data from strapi with its API but I am not able to fetch data in the NEXTJS application.
Here is my code from
file path => post/[slug]/page.js
const getPost = async (id) => {
const data = await fetch(`http://127.0.0.1:1337/api/posts?filters[Permalink][$eq]=${id}`);
const post = await data.json();
return post;
};
export const generateStaticParams = async () => {
const data = await fetch("http://127.0.0.1:1337/api/posts")
// const data = await fetch("http://127.0.0.1:1337/api/posts?filters[Permalink][$eq]=my-first-post")
const posts = await data.json()
return posts.data.map(post => ({
params: {
slug: post.attributes.permalink
}
}))
}
export default async function Home({ params: { slug } }) {
const post = await getPost(slug)
return (
<>
<div id={post.id}></div>
<ul>
{post.data.map(item => (
<>
<li key={item.id}>{item.attributes.Title}</li>
</>
))}
</ul>
</>
)
}
MY STRAPI API DATA
Below is my API DATA Generated by Strapi and fetched from Postman
{
"data": [
{
"id": 2,
"attributes": {
"Title": "My Second Post",
"Meta_Description": "Some Description",
"Content": "Some Text",
"createdAt": "2023-11-27T14:42:07.787Z",
"updatedAt": "2023-11-27T14:50:16.707Z",
"publishedAt": "2023-11-27T14:42:29.807Z",
"Block_editor": null,
"Permalink": "my-second-post"
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 1
}
}
}
Also, I have tested the code with https://jsonplaceholder.typicode.com/posts with some changes and its working successfully
NOTE:- I am using Next JS - APP Directory