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*/
]
}
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
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?
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 } }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.