Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting props as undefined in component returned from getStaticProps

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

like image 509
Kunal Rai Avatar asked Mar 02 '23 04:03

Kunal Rai


2 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

like image 150
Closery Avatar answered Mar 04 '23 17:03

Closery


getStaticProps (Static Generation): Fetch data at build time.

Maybe you could try to rebuild your app to see if it works.

like image 23
dongnhan Avatar answered Mar 04 '23 18:03

dongnhan