I have returned json response from getStaticProps and console logged it in getStaticProps to verify correct json response. So, fetch is working fine and I am getting correct response from API.
import Layout from '../components/layout';
import fetch from 'isomorphic-unfetch';
const Index = ({data}) => {
console.log(data)
return (
<Layout>
<div>
<h1>Welcome to Next Application</h1>
<h3>Users List</h3>
{data ?
data.map((item, i) => {
return (
<li key={i}>{item.name}</li>
)
}):
<span>Loading...</span>
}
</div>
</Layout>
);
}
export const getStaticProps = async () => {
const response = await fetch(`https://jsonplaceholder.typicode.com/users`);
const data = await response.json();
console.log(data);
return {
props:{
data
}
}
}
export default Index;
Getting data as undefined in Index component. What am I missing ?
My Output - https://ibb.co/Ns9143C Github - https://github.com/ho-dor/next-poc
The problem is in your custom App file, if your remove your custom App wrapper your problem will solve but if you want to keep custom app wrapper just update your _app.js
like this:
import App from 'next/app';
const MyApp = ({ Component, props }) => {
return (
<div className="MyApp">
<p>_app.js file</p>
<Component {...props} />
</div>
);
};
MyApp.getInitialProps = async (appContext) => {
// calls page's `getInitialProps` and fills `appProps.pageProps`
const appProps = await App.getInitialProps(appContext);
return { ...appProps };
};
export default App;
For more info check here: Custom App - NextJS
getStaticProps
(Static Generation): Fetch data at build time.
Maybe you could try to rebuild your app to see if it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With