Peter3 Peter3 - 2 months ago 14x
React JSX Question

Submitting result of Get call to react class

I have been trying to learn about being a full-stack web developer. I have decided to use the MERN stack. I am in the midst of trying to write my first "full-stack" application. However I can't seem to figure out how to store the data from my get call and submit it to the class as a property. The get call will reach an end point I have set up in nodejs which will make a call to Mongo and return an array of numbers. The get call below works as I can console.log the number of elements in that array. I have tried a number of different ways but I can't seem to figure out how to get the number out of the THEN promise and into my class to display on the screen. Any help would be greatly appreciated!

const React = require('react');
const ReactDOM = require('react-dom');
const axios = require('axios');

//call with npm build

var num = axios.get('/api').then(result => {

//Only show how many unused coupons are left.

var Message = React.createClass({

render: function () {

return <h1>There are {this.props.number} coupons left!</h1>

}//end of of render outer function

ReactDOM.render(<Message number={num} />,document.getElementById('content'))


First, api call is an asynchronous operation, you can't call in a sync way.

And, instead of returning derived from api value, axios.get function returns Promise, which resolving this value.

Correct solution would be create <App /> component and call to api in componentDidMount lifecycle callback, set corresponding state variable on success response and render <Message /> component providing this variable to it.

Look at example:

var App = React.createClass({
  getInitialState() {
    return {
      num: null

  componentDidMount() {
    var num = axios.get('/api').then(result => {
      this.setState({ num: });

  render() {
    if (this.state.num) {
      return <Message number={this.state.num} />
    return <div />

ReactDOM.render(<App />,document.getElementById('content'))