Reputation: 67
I am creating a blog in Next.js and using Strapi headless CMS as backend.
I was trying to get data from the API I made from Strapi.
For fetching data I made ./client.js
export default class StrapiClient{
constructor(){}
/*API_URL = "http://localhost:1337/api/"*/
async fetchData(path){
const url = `${process.env.API_URL}${path}`
const res = await fetch(url)
const posts = await res.json()
return posts
}}
and imported it to ./components/blog.js
import StrapiClient from '../client'
const Client = new StrapiClient
export const getStaticProps = async () => {
const posts = await Client.fetchData(`articles`)
return{
props: {
posts,
}
}
};
const Blog = ({posts}) => {
return (
<div>
{posts.data.map((element) => {
return(
<div key={element.id}>
<h1 className=" text-2xl">{element.attributes.title}</h1>
</div>
)
})}
</div>
);
};
export default Blog;
but I got error
TypeError: Cannot read properties of undefined (reading 'data')
and here is the structure of data I was using
{
"data" : [
"id" /*string*/
]
}
Upvotes: 1
Views: 3842
Reputation: 2018
From next.js documentation the getStaticPaths method is used to define a list of paths to be statically generated but to fetch data for page you need to use getStaticProps:
export async function getStaticProps() {
const posts = await Client.fetchData(`articles`);
return {
props: {
posts,
},
}
}
Or fetch data using getServerSideProps without use getStaticPaths
:
export async function getServerSideProps() {
const posts = await Client.fetchData(`articles`);
return { props: { posts } }
}
Upvotes: 1
Reputation: 4894
You need to await
the async function to get data from Promise
export const getStaticProps = async () => {
const posts = await Client.fetchData(`articles`)
return{
props: {
posts,
}
}
};
Async functions always return a promise
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Upvotes: 1
Reputation: 177
const posts = Client.fetchData(`articles`)
I think you need to await
for the fetchData.
Edit:
I just noticed you are using getStaticPaths
function instead of getStaticProps
. Can you please change the name and try again?
Upvotes: 1