Home > database >  NextJs - question on data fetching in a functional component
NextJs - question on data fetching in a functional component

Time:04-06

I am new to typescript & NextJs. I have a question about this code


const Home: NextPage = ({characters}:any) => {  
return (      
  <div>          
    {JSON.stringify(characters)}        
 </div>  
)}

export const getStaticProps:GetStaticProps = async(context)=>{  
const res = await fetch("https://rickandmortyapi.com/api/character")  
const { results } = await res.json();  
return{    
      props:{      
            characters: results   }  }}


export default Home

The const getStaticProps returns an object prop, how does it get into Home? I don't see home calling it

Home: NextPage = ({characters}:any) it's expecting a characters object of any. How does it know that prop is the one to read from?

CodePudding user response:

From Next.js docs:

Exporting a function called getStaticProps will pre-render a page at build time using the props returned from the function

These can only be declared on page components, because of that, at build-time each page could only have one of these functions, if it has, it will execute and send the props down to the page component.

  • Related