JavaScript - React JS

3

How do I get a part of a JSON, put in a variable, and then play this variable in a widget of my layout?

Example: ( link ) I want to get the value of "ip", and put in my widget instead of the value '1,410' .

constructor(props){super(props);this.state={data:[]}}componentDidMount(){letURL='http://ip.jsontest.com/'fetch(URL).then(function(response){letdata=response.json()returndata;}).then((json)=>{console.log('parsedjson',json)data:json;})}render(){return(<divclassName="container text-center">
      <div className="row">
      <h1> Quero que apareca o Ip aqui = {this.state.data.ip}</h1>
    
asked by anonymous 04.11.2017 / 18:13

2 answers

3

You have to use setState , that's what in the React API does call the render again.

An example would look like this:

constructor(props) {
  super(props);
  this.state = {
    data: {}
  }
}
componentDidMount(){
        let URL = 'http://ip.jsontest.com/'
        fetch(URL).then(response => this.setState({data: response.json()});

}
render(){
    return(
      <div className="container text-center">
          <div className="row">
          <h1>{this.state.data.ip}</h1>
    
04.11.2017 / 19:14
0

You could already use asynchronous calls to your application using async / await and also a try / catch to deal with call success and error.

example:

constructor(props) {
  super(props);
  this.state = {
    data: {}
  }
}
async componentDidMount(){
  let URL = 'http://ip.jsontest.com/'

  try{
    const response = await fetch(URL)
    this.setState({data: response.json()})
  } catch(err){
    console.log(err.response)
  }
}
render(){
    return(
      <div className="container text-center">
          <div className="row">
          <h1>{this.state.data.ip}</h1>
    
13.11.2018 / 12:42