MatDoak
MatDoak

Reputation: 142

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 property 'map' of undefined" Any ideas on how to fix?

import axios from "axios"

const CosmeticsApi = ({cosmetics}) => {
  return (
    <div>
      {cosmetics.map(cosmetic =>(
        <div key={cosmetic.id}>
          <h4>{cosmetic.name}</h4>
        </div>
      ))}
    </div>
  )
}

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

export default CosmeticsApi;

Upvotes: 0

Views: 3151

Answers (2)

Ryan Le
Ryan Le

Reputation: 8422

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 here
    return { cosmetics };
  } catch (error) {
    return {error};
  };
};

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

const CosmeticsApi = ({cosmetics}) => {
  return (
    <div>
      {cosmetics && cosmetics.map(cosmetic =>(
        <div key={cosmetic.id}>
          <h4>{cosmetic.name}</h4>
        </div>
      ))}
    </div>
  )
}

Working Example:

Edit next.js-getInitialProps-redux (forked)

Upvotes: 1

James Lin
James Lin

Reputation: 182

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.

Upvotes: 0

Related Questions