1

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,
        ....,
    }
]
1
  • 1
    this.state.products[0] does not have property name. Commented Apr 30, 2019 at 9:05

1 Answer 1

2

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}     
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.