react – How to pass a JSON object to another function?

Question:

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

  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 graph receives the JSON that I acquired through GET, but to show it on the screen it will appear null, as it is in the then.

Answer:

This is because json will be received asynchronously.

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

Then it uses setState and if necessary returns null until the data 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>);
}
Scroll to Top