0

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;
1
  • details && details.map assuming details is really an array Commented Sep 6, 2020 at 20:29

2 Answers 2

2

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

2 Comments

Thanks alot, it fixed my error but why it should be data instead of details? or something else? is data predefined result-set from the fetch call?
No, that is just the structure of the returned JSON from that specific API.
1

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.

2 Comments

why it should be data instead of details? or something else? is data predefined result-set from the fetch call?
@Rohan Just enter the url - dummy.restapiexample.com/api/v1/employees on your browser and check the response object that you get. In that object, there only exists data as a key for response object and no details and hence...

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.