Rohan
Rohan

Reputation: 109

React basic api call issue

I am trying basic react js api data display on to the DOM.

I am getting this error:

On the console I dont get any errors but it gives TypeError: Cannot read property 'map' of undefine error on the page.


class App extends React.Component {
  constructor(props)
  {
    super(props);
    this.state = {
     details: [],
     isLoaded: false
    }
   
  }
  
  componentDidMount()
  {
    fetch("https://dummy.restapiexample.com/api/v1/employees")
    .then(res => res.json())
    .then(
      (result) => {
        this.setState({
          isLoaded: true,
          details: result.details
        })
      }
    )
  }

 
  render() {
    const { isLoaded, details} = this.state;

    if(!isLoaded)
    {
      return <div> Loading ...... </div> 
    }

    return (
    <ul>
      {details.map(detail => (
        <li key={detail.employee_name}> {detail.employee_name} </li>
      ))}
    </ul>
    );
  }
  
}

export default App;

Upvotes: 0

Views: 226

Answers (2)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

Your code should work fine if the response you are setting to details is an array.In the fetch url you are trying to fetch from, the response doesn't have any details field. Change it to result.data and it should work fine.

Also Maybe try changing details.map(...) to details && details.map(....) This should solve the error if you are getting it due to delay in setting the result.data into details from the fetch. This change would also make sure that if details is undefined (as it currently is in your code), then the map function would never execute and you won't be thrown the error.

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

The endpoint you use returns data, not details.

So the

this.setState({
      isLoaded: true,
      details: result.details
    })

should really become

this.setState({
      isLoaded: true,
      details: result.data
    })

Upvotes: 2

Related Questions