0

I'm getting the below error using getStaticProps(). What's the problem here? Using nextjs and I'm passing the returned value as props to a component. I have no idea what's happening here and have tried several things (await, JSON.stringify()) but nothing is working. When I run the api route separately it works so I know the api route is good. Also when I use the names constant it works as well.

export async function getStaticProps(){
    
    //const names = {fname: "jim", age: "bob", grade: 10} 
    const res = axios.get("/api/teacher/loadstudents")
    .then(res=>{                        
        console.log(res.data);          
    })
    .catch(err => {console.log(err)}) 
    const studentdata =  JSON.stringify(res.data);
    
    return {
        props:{data: studentdata}
    }
 }
 

const TeacherMainPage = (props)=>{
    var classCode = "XZLE123"; 
    console.log("These are the props: ", props) ;
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    It's not recommended to make a call to one of your API endpoints inside `getStaticProps` or `getServerSideProps`. You should be writing the server-side code directly on these functions. More information [here](https://nextjs.org/docs/basic-features/data-fetching/get-static-props#write-server-side-code-directly). – ivanatias Aug 17 '22 at 04:07

1 Answers1

0

The issue is that your code execution is not happening top to bottom as you think, axios.get is an async call, so then executed asynchronously, but JSON.stringyfy executes synchronously.

To correct it, you can put await before axios.get to wait for the promise to resolve then execute JSON.stringify followed by return. It is also a good idea to use try catch here if going await route.

 export async function getStaticProps(){
    try { 
        const res = await axios.get("/api/teacher/loadstudents");

        const studentdata =  JSON.stringify(res.data);
    
        return {
            props:{ data: studentdata }
        }
    } catch(error) {
        console.log(error)
        return {};
    }
 }

One thing to note though, probably JSON.stringify is not needed here.

Suman Kundu
  • 1,702
  • 15
  • 22