I am trying to fetch posts from jsonplaceholder and using the getStaticProps method .inside i send a HTTP request through axios package and try to get data but it always gives undefined
here is the code:
import { Fragment } from "react";
import axios from "axios";
const Main = ({data}) => {
console.log(data);
return (
<Fragment>
<section className="main mt-3">
<div className="container-lg">
<div className="text-center">
<h3>
<span className="text-primary fw-bold display-5 ">Welcome</span>{" "}
<span className="text-dark fw-bold display-5 ">Next</span>
</h3>
<p className="text-muted">Lorem ipsum dolor sit amet.</p>
</div>
</div>
</section>
</Fragment>
);
};
export const getStaticProps = async () => {
const {data} = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return {
props: {
data
},
};
};
export default Main;
CodePudding user response:
I am also using same API while learning Next JS .. see solution below.
response from API is under response.data
export async function getStaticProps() {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return { props: { posts: response.data } };
}
CodePudding user response:
the method is totally correct , but if someone has previous bugs then it will not work properly try removing it and try again , the second mistake i did was i put the child component in parent and in child i was making a request ,the right method would be to do the request in parent and then pass the data to child