Getting props as undefined in component returned from getStaticProps

Viewed 8855

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

3 Answers

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.

You are using custom _app component in your source code. If you're using custom _app component, you need to check if the components have static components and trigger that manually. This will be done in custom app component itself.

If you're not using it, then you won't face any issue.

You can follow this approach I used for getInitialProps in my custom _app here

Related