Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: Cannot read properties of undefined (reading 'map') in NextJS – getStaticPaths

I have a problem with dynamic routing in next 13, I have dynamic page [id].js and trying to fetch the data

 const res = await fetch(`myAPI`);
 const resData  = await res.json();
    
 const paths = resData.data.map((r) => ({
      params: { id: r.id}
 }));

 return {
     paths,
     fallback: false
 }

It does not work and gives me error with .map function, if I hard code the path it works without any issue and give me correct output data

Hard coded example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  paths: [
    {params: { id: '67'}}
  ],

I know that my map function should be correct as I tested in inside the component

  axios
  .get(`myAPI`)
  .then((response) => {
    console.log(response.data.map((res) => {return(res.id)}))
  })

console output in component return data without complaining, why I cannot achieve it in getStaticPath?

>Solution :

resData is already your array of objects, so you can "skip" data:

const res = await fetch(`myAPI`);
const resData  = await res.json();

const paths = resData.map((r) => ({
     params: { id: r.id}
}));

The reason why when using Axios you have to use data, is because Axios already gets the response data as JSON for you (as data). You were confusing Axios’ response for resData.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading