0
votes

In my componentDidMount() I am making an API call "invokeservice" to fetch some data, this call then sets a state object that I use in my render.

The problem I am having is that the invokeservice is not being called and set the first time that the page is loaded, however when I refresh the page the invokeservice returns the data fine and the rest of the script will run. It's only the first time that it returns an null value.

Is it possible to call this invoke service in render function and keep the data ready and display it when user tries to load this page.

TRIED: 1.read that ComponentDidMount is called only after 1st initial render. 2. {this.invokeservice()} i tried to call in render function before return which did initial render but after 5sec it was blank and then again 5sec later it is filled again with values.

render function

public render() {
    return (
        <div className="monitor">
          <div className="monitor__table">                   
            {this.monitorrow(translate("cpu"), this.state.cpuString)}
            {this.monitorrow(translate("memory"), this.state.pmemoryString)}
          </div>
        </div>
    );
  }

constructor

constructor(props) {
    super(props);
    this.state = {
      cpu: 0,
      cpuString: ""
    };
    setInterval(() => this.invokeservice(), 5000);
  }

componentdidMount

  public componentDidMount() {
    this.invokeservice();
  }

invokeservice

private invokeservice() {

    var client = new HttpClient();

    var url = this.props.baseUrl + '//getMonitorUsage' + '?NC=' + Date.now().toString();

    client.get(url, (response) => {
        this.setState({
          cpu: JSONResponse.GetSystemStateResult.CPUusage

        });
      }
    }
    });
  }

function

monitorrow(left,right) {
    return (
      <div className="table__row">
        <div className="table__cell__left">
          <Text>{left}</Text>
        </div>
        { right &&
          (<div className="table__cell__right">
            <Text>{right}</Text>
          </div>)
        }
      </div>  
    );
  }
1
It's only the first time that it returns an null value. what exactly is returning null? - messerbill
first time it returns an initial value which is empty string as defined in constructor this.state. - user28

1 Answers

2
votes

It is expected.

From the react docs:

These methods are called in the following order when an instance of a component is being created and inserted into the DOM:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

Ref: https://reactjs.org/docs/react-component.html


There is componentWillMount which will be called before render(). But is it not advised to be used. Read more on the official docs https://reactjs.org/docs/react-component.html#unsafe_componentwillmount