Skip to content Skip to sidebar Skip to footer

Axios Api Request In Nextjs Returning Cannot Read Property Of 'map' Of Undefined

Okay so I'm trying to return data from this API endpoint https://fortnite-api.com/v2/cosmetics/br using axios is NextJs but Next keeps returning the error 'TypeError: Cannot read p

Solution 1:

Like the previous question, you will need to access another layer of data:

And it's getInitialProps not getInitalProps.. Oh dear, you've got me awhile.

CosmeticsApi.getInitialProps = async ctx => {
  try {
    const res = await axios.get('https://fortnite-api.com/v2/cosmetics/br');
    const cosmetics = res.data.data;  // <-- Access one more data object herereturn { cosmetics };
  } catch (error) {
    return {error};
  };
};

And you might want to check if the array exists before mapping it:

constCosmeticsApi = ({cosmetics}) => {
  return (
    <div>
      {cosmetics && cosmetics.map(cosmetic =>(
        <divkey={cosmetic.id}><h4>{cosmetic.name}</h4></div>
      ))}
    </div>
  )
}

Working Example:

Edit next.js-getInitialProps-redux (forked)

Solution 2:

I have solved the issue.

It occurred because I broke a simple rule.

According to the next.js document, there is a note saying

Note: getInitialProps can not be used in children components. Only in pages.

So when I fetched that data at index.js, it successfully gets the data I want to have.

Thought I could use getInitialProps in any components just like componentDidMount.

That was a problem.

Post a Comment for "Axios Api Request In Nextjs Returning Cannot Read Property Of 'map' Of Undefined"