Reputation: 419
I am having trouble doing a fetch according to the documentation available on the Next.js website. I have tried to console the props, which I can't get to show up. I don't have experience with Next, trying to mirror it to React, but unfortunately it's not working. How can I do a fetch using getStaticProps? I have a tutorial that is using getInitialProps for an older version of Next.js, but I am trying to follow their new documentation. Here is the starter code I have so far:
import React, { Component } from 'react';
// import fetch from 'node-fetch'
class Index extends Component {
state = {}
getStaticProps = async () => {
// Call an external API endpoint to get posts.
console.log('fetching data')
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
const posts = await res.json()
return {
props: {
posts,
},
}
}
render() {
console.log(this.props)
return (
<div>
<h1>Our Index Page!!</h1>
</div>
);
}
}
export default Index
Upvotes: 0
Views: 5861
Reputation: 3780
From the docs:
If you export an async function called
getStaticProps
from a page, Next.js will pre-render this page at build time using the props returned bygetStaticProps
.
That means that instead of having your getStaticProps
inside the component, export it as such:
import React, { Component } from 'react';
// import fetch from 'node-fetch'
class Index extends Component {
state = {}
render() {
console.log(this.props)
return (
<div>
<h1>Our Index Page!!</h1>
</div>
);
}
}
export const getStaticProps = async () => {
// Call an external API endpoint to get posts.
console.log('fetching data')
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
const posts = await res.json()
return {
props: {
posts,
},
}
}
export default Index
Upvotes: 1