Using fetch to render json data in a reaction application

I am trying to display JSON about the location of the person from the api in my client application. I am a big newbie newbie, so please come with me.

I use isomorphic-fetch to access data from api, I can add a basic test, and it logs data correctly 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 solve is how I can accept this answer and display it in my component, which currently looks like this (in this example, the code below the data comes from the local json file, so I need to combine them together).

I tried setting componentDidMount, but could have plunged into the syntax so that it kept breaking, I also checked the redux actions, but it blew my mind.

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>
    )
}
+4
1

componentDidMount 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 });
  });
}

:

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>
})
+10

Source: https://habr.com/ru/post/1651732/


All Articles