tarek hassan
tarek hassan

Reputation: 802

can't map array after actually printing the array inside passed data

I am passing data to presentations (stateless) class, the data is passed and I can print the array of prices passed inside it, however when I try to map this array I get an error ('Cannot read property 'map' of undefined')

The codesandbox code here

const CoinCharts = ({prices}) => (
      <div className='section'>
        // this console.log get an array printed
    {console.log( ( prices.Data ) )}


    {prices.Data.map( (price) => 
     <div> something here </div>
    )}
)

The index.js just passed the data like this

 <div className='column'> <CoinCharts prices={this.state.prices} /> </div>

The data passes ok and prints ok, but doesn't map

Upvotes: 1

Views: 26

Answers (2)

vitomadio
vitomadio

Reputation: 1140

I recommend you to change this line:

prices: response.data

to this one

prices: response.data.Data

that should do the job.

Upvotes: 0

weibenfalk
weibenfalk

Reputation: 902

This is happening because at the first render there's nothing in prices.Data. You're grabbing the data with a promise from Axios. So you have to check for the data to actually be there otherwise you'll get this error. You can do that in many ways but one is this:

const CoinCharts = ({prices}) => (
      <div className='section'>
        // this console.log get an array printed
    {console.log( ( prices.Data ) )}


     { prices.Data ? prices.Data.map( (price, key) =>
      <div key={key} >Something here</div> 
     ) : null }
)

Upvotes: 1

Related Questions