Ash
Ash

Reputation: 347

Using fetch to render json data in react app

I am trying to render some JSON about a person's location from an api in my react app.

I am using isomorphic-fetch to access the data from the API I can add the base test in and it correctly logs the data using below.

 require('isomorphic-fetch');
 require('es6-promise').polyfill();

 var url = 'http://localhost:3000/api/data'

 fetch(url)
    .then(function(response) {
    if (response.status >= 400) {
       throw new Error("Bad response from server");
    }
    return response.json();
  })
  .then(function(data) {
     console.log(data);
  });

What i'm trying to work out is how I can take this response and render it in my component which currently looks like this (in this example code below data is coming from local json file so i need to merge them together).

I've attempted to set up componentDidMount but could get my head around the syntax so it kept breaking, I also checked out redux actions but that exploded my brain.

const personLoc = Object.keys(data.person.loc).map((content, idx) => {
    const items = data.person.loc[content].map((item, i) => (
        <p key={i}>{item.text}</p>
    ))

    return <div key={idx}>{items}</div>
})

export default function PersonLocation() {
    return (
        <div className="bio__location">
            {personLoc}
        </div>
    )
}

Upvotes: 6

Views: 42654

Answers (1)

vijayst
vijayst

Reputation: 21826

componentDidMount should setState:

componentDidMount() {    
  var that = this;
  var url = 'http://localhost:3000/api/data'

  fetch(url)
  .then(function(response) {
    if (response.status >= 400) {
      throw new Error("Bad response from server");
    }
    return response.json();
  })
  .then(function(data) {
    that.setState({ person: data.person });
  });
}

The render component should map the state:

const personLoc = Object.keys(this.state.person.loc).map((content, idx) => {
    const items = this.state.person.loc[content].map((item, i) => (
        <p key={i}>{item.text}</p>
    ))

    return <div key={idx}>{items}</div>
})

Upvotes: 16

Related Questions