takuma bo
takuma bo

Reputation: 194

TypeError: Cannot read property 'map' of undefined. What should I fix?

I got the error when I tried to get some datas from api.

Then I searched how to solve this error but I couldn't solve. I want to solove this error. I don't know Why do I get this error. What should I fix my code ?? Please tell me any ideas. thank you for reading !

this is my error.

TypeError: Cannot read property 'map' of undefined

and message image. enter image description here

this is my code.

import React,{ Component } from 'react';

class Exchange extends Component {
  constructor(props){
    super(props);
    this.state = {
      isLoaded: false,
      items: [],
    }
  }
  componentDidMount(){
    fetch('https://api.exchangeratesapi.io/latest')
    .then(res => res.json())
    .then(json => {
      this.setState({
        isLoaded: true,
        items: json.items,
      })
    })
    }

    render(){
      var { items,isLoaded } = this.state;

      if(!isLoaded){
        return <div>...Loading</div>;
      }else{
        return (
          <div>
            <ul>
              {items.map(item =>(
                <li key={item.rates}>{item.CAD}</li>
              ))}
            </ul>
          </div>
        )
      }
    }
}

 export default Exchange;

and this is using api. enter image description here

Upvotes: 1

Views: 2467

Answers (3)

balaji b r k
balaji b r k

Reputation: 65

To change the state of the array this.setState({ items: [...this.state.items, itemsArr] }) If the your response of API is array you can follow the above way.

But in your API response it seems like object, to push object into an array gothrough the link

Upvotes: 0

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

I think the way you access the data from api is wrong it should be

this.setState({
    isLoaded: true,
    items: json.rates //json.rates not json.items
});

and when rendering it, map expecting a array so you have do something like this

<ul>
    {Object.keys(items).map(key => (
        <li key={key}>{key} - {items[key]}</li>
     ))}
</ul>

Demo

Upvotes: 1

Smile
Smile

Reputation: 4088

There is no attribute items in the json response. That's why items is undefined after following statement : items: json.items.

Also, map() is only applicable to array. Response from the API you are calling is not Array.

You can modify code something like

this.setState({
    isLoaded: true,
    items: json,
})

And

<ul>              
    <li>{items.rates.CAD}</li>
</ul>

Upvotes: 0

Related Questions