Javascript - React JS

Asked

Viewed 434 times

4

How do I take a part of a JSON, put it in a variable and then throw that variable in a "Widget" of my layout?

Example: (http://ip.jsontest.com/) I want to take the value of "ip", and put in my widget instead of the value '1,410'.

inserir a descrição da imagem aqui

constructor(props) {
  super(props);
  this.state = {
      data:[]
      }
  }
  componentDidMount(){
        let URL = 'http://ip.jsontest.com/'
           fetch(URL)
           .then(function(response) {
              let data = response.json()
              return data;
           })
           .then((json) => {
              console.log('parsed json', json)
              data : json;
           })
  }
 render(){
 return(
  <div className="container text-center">
      <div className="row">
      <h1> Quero que apareca o Ip aqui = {this.state.data.ip}</h1>
  • Instead of just data : json; you have to use this.setState({data : json}); you already tested that?

  • It worked with what you gave me, Thank you so much ! :D

  • Henrique: usa this.state = {&#xA; data: {}&#xA; }, with an object to be more correct, since it will be an object in the future when json arrives.

2 answers

4


You have to use the setState, This is what the React API calls render again.

An example would be 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>

1

You could already use asyncrons calls for your application using async/await and also a Try/catch to handle Success and call 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.