user12367472
user12367472

Reputation:

can't seem to retrieve data from this api in react

import react from 'react';    
export default class App extends react.Component {
  state = {
    loading: true,
    person: null,
  }

having difficulty in getting the data to be rendered. data does show on console log but won't display names on react page please help.

any help would be appreciated thank you

Upvotes: 1

Views: 247

Answers (2)

user12367472
user12367472

Reputation:

I actually did it a different way by using ! {this.state.loading || !this.state.person ? (

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370589

This is the API response:

[{"id":1,"title":"Mr","firstName":"Danny","lastName":"Dyer","dob":"24/07/1977","active":true},{"id":2,"title":"Mr","firstName":"Nicholas","lastName":"Cage","dob":"07/01/1964","active":true},{"id":3,"title":"Miss","firstName":"Emma","lastName":"Watson","dob":"15/04/1990","active":true},{"id":4,"title":"Prof","firstName":"Bryan","lastName":"Cox","dob":"03/03/1968","active":true}]

It's an array of objects. data.res[0] would make sense only if the API response was an object containing a res property, eg

{
  "res": [
    {"id":1, ...

So, change your code from

person: data.res[0]

to

person: data[0]

and from

<div>{this.state.person.name.title}</div>
<div>{this.state.person.name.first}</div>
<div>{this.state.person.name.last}</div>

to

<div>{this.state.person.title}</div>
<div>{this.state.person.firstName}</div>
<div>{this.state.person.lastName}</div>

to properly navigate the data.

(also make sure to enclose the url in string delimiters ' or ", not < >)

Live snippet:

class App extends React.Component {
  state = {
    loading: true,
    person: null,
  }
  componentDidMount() {
    const url = 'https://api.jsonbin.io/b/5e9ef690435f5604bb4567dd';
    fetch(url)
      .then(response => response.json())
      .then(data => this.setState({ person: data[0], loading: false }));
  }

  render() {
    return (
      <div>
        {this.state.loading || !this.state.person ? (
          <div>loading...</div>
        ) : (
            <div>
              <div>{this.state.person.title}</div>
              <div>{this.state.person.firstName}</div>
              <div>{this.state.person.lastName}</div>
            </div>
          )}
      </div>
    );
  }
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

Upvotes: 1

Related Questions