Amitco
Amitco

Reputation: 55

ReactJS - TypeError: Cannot read property 'name' of undefined

I'm fetching data from an API and I want to show on the screen some objects (for example 'name' object) and I'm getting the following error:

"TypeError: Cannot read property 'name' of undefined"

I already tried to show data after the api request (with booleans)

Does anyone know what might be the problem?

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      products: {},
    }
    this.fetchDevices = this.fetchDevices.bind(this);
}

async fetchDevices() {
  const url = 'my url';
  const response = await fetch(url, {method : 'GET', headers : headers});
  const data = await response.json()
  this.setState({products : data.value})
}

componentDidMount() {
  this.fetchDevices();
}

render() {
  return (
    <div>
      {this.state.products ? <p>{this.state.products[0].name}</p> : null}     
    </div>
  )}
}

export default App

{
"value": [
    {
        "urn": null,
        "name": "New_COMEC",
        "description": null,
        "icon": "icon-energy-meter",
        "customIdFormat": null,
        "customIdDisplay": true,
        "customIdRequired": true,
        "serialNumberFormat": null,
        "serialNumberDisplay": true,
        "serialNumberRequired": false,
        ....,
    }
]

Upvotes: 1

Views: 2410

Answers (1)

JiN
JiN

Reputation: 828

You have initialized your products state as an empty object instead of an array. The render method will be called before your fetch call, hence the app breaks. Since you initialized as an object,

{this.state.products ? <p>{this.state.products[0].name}</p> : null}

is true in the initial render, so it tries to get the first array element when the state is actually an object at that time..

Your code ought to be like

class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
      products: [],
    };

and

{Array.isArray(this.state.products) && this.state.products[0] ? <p>{this.state.products[0].name}</p> : null}     

Upvotes: 2

Related Questions