How to pass a JSON object to another function?

Asked

Viewed 626 times

3

In the 'componentDidMount' function of REACT I get the json of a link in question, but in the 'render' I cannot pass these objects because the object is in a '.then' in the first function. How can I accomplish that?

  componentDidMount(){
    let URL = 'http://algumaUrl'
       fetch(URL)
       .then(function(response) {
          let data = response.json()
          return data;
       })
       .then((json) => {
          console.log(json)
          // this.setState({data : json});
          this.setState({data : json});
          grafico = json;
       })
       .catch(function(ex) {
          console.log('parsing failed', ex)
       })
  }

  render () {

    console.log('grafico ', grafico);
}

My chart receives the JSON that I acquired through GET, but to show on screen it will appear null, because the same is in the then.

1 answer

1


This happens because the json will be received asynchronously.

The concept to take into account in React is that everything is zeroed at the beginning. And then they arrive and change values, everything via props and state. If for example you have an object coming from that ajax, you have to have the function render a solution for the code to work even before that value arrives. And everything that is inserted on the page or comes via props or vis setState. Do grafico = json; to use outside this method is something anti-pattern, past, non-reactive.

Then use the setState and if necessary returns null until the date object exists:

  componentDidMount(){
    let URL = 'http://algumaUrl'
       fetch(URL)
       .then(function(response) {
          let data = response.json()
          return data;
       })
       .then((json) => {
          this.setState({data : json});
       })
       .catch(function(ex) {
          console.log('parsing failed', ex)
       })
  }

  render () {
    const data = this.state.data;
    if (Object.keys(this.data).length == 0) return null;
    else return (<p>{JSON.stringify(data)}</p>);
}

Browser other questions tagged

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