Home > Net >  TypeError: Cannot read properties of undefined (reading 'map') in NextJS - getStaticPaths
TypeError: Cannot read properties of undefined (reading 'map') in NextJS - getStaticPaths

Time:11-02

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:

  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?

CodePudding user response:

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.

  • Related