Search code examples
javascriptreactjsfunctionreturn

How to properly return value from a data inside the function


Im new to javascript and started to learn amazing stuff from it. As the code below how can I be able to return the value of index inside getData().then(data => {. getData function has json response values.

subPatternStart() {
  getData().then(data => {
    var patternStart = 1525750500000;
    var index = 0;

    for (var i = 0; i < data.length; i++) {
      if ( patternStart >= data[i].time && patternStart < data[i+1].time ) {
        //...somecode
      }
    }
    console.log("Index:" , index);
  })
}

What I want to achieve is that when I call this function I should ONLY get the value of index, which in this case the console log value is equivalent into 1.

I have this in my render method.

render() {
  index={this.subPatternStart()}
}

In this simple code, it returns the exact value in the render method, and I want to do something like this.

subPatternStart() {
  var patternStart = 1;
  return patternStart;
}

Solution

  • You should set the state of the component with the value you get from getData. Then React can update it self and render the page. For example

    import React from 'react';
    
    class App extends React.Component {
    
      constructor(props) {
        super(props);
    
        this.state = {
          index: 0
        }
      }
    
      subPatternStart() {
        getData().then(data => {
          var patternStart = 1525750500000;
          var index = 0;
    
          for (var i = 0; i < data.length; i++) {
            if (patternStart >= data[i].time && patternStart < data[i + 1].time) {
              //...somecode
            }
          }
          this.setState({
            index: index
          });
        })
      }
      render() {
        index =  this.state.index
      }
    }