Masnad Nihit
Masnad Nihit

Reputation: 1996

Error while binding array to state

I am trying to use fetch to get json data from my back end and then put it on a array, and show it on the screen, for now on the console log. I am trying to store the information I get back in a array called data which I initialized in getinistate, and then put json data in it while the fetch call is done. For now The error I am reciving is that console.log is basically empty.

Here is the code.

<body>
  <div id="reactBinding"></div>

<script type="text/babel">
  var Heading = React.createClass({
    getInitialState: function() {
        return {
          data: [],
          amount : 1000
        };
    },
    handleChange: function(event){
      this.setState({amount : event.target.value});
    },
      loadCommentsFromServer: function() {
        var value = {
          method : 'GET' ,
          headers : {
            'Accept': 'application/json',
            'contentType' : 'application/x-www-form-urlencoded',
          },
          body : ({
            amount : this.state.amount
          })
        };
          fetch('http://localhost:3000/getIOT', value)
          .then((response) => response.json())
          .then((responseData) =>{
            responseData : this.state.data 
          })
          .catch(function(err){
           console.log(err);
        });
      },
      showTable : function(){
        console.log(data);
      },
      render : function(){
        var amount = this.state.amount;
        return(
          <div className="container">
            <div className="row">
              <div classname="col-xs-4 col-xs-offset-4">
                <div className="text-center">
                  <h1>{this.props.name}</h1>
                  <h2> {amount} </h2>
                  <input type="text" value={amount} onChange={this.handleChange} />
                  <button onClick={this.showTable}>Show Table</button>
                  <button onClick={this.loadCommentsFromServer}> Submit </button>
                </div>
              </div>
            </div>
          </div>
        );
      }
  });
ReactDOM.render(
    <div>
      <Heading
      name="React JS"
      >
      </Heading>
      </div>
  , document.getElementById('reactBinding'));
</script>
</body>

So again, what I want to do is get the information from fetch, put it in the variable called data array and then when someone clicks showTable, it should console.log the array out. Totally new to react so need a bit of handholding since this is the first time I am writing it. If this code is a bit too messy it would be great someone could help show me how to write a simple fetch.

Also if you have time it would be great if someone could explain how can I display the array in a table. in the showTable part.

Upvotes: 0

Views: 58

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104379

You need to use the setState to store the data in state variable once you get the response, like this:

fetch('http://localhost:3000/getIOT', value)
  .then((response) => response.json())
  .then((responseData) =>{
     //responseData : this.state.data 
     this.setState({data: responseData}); // use this line
  })

put the console.log in render function, it will print the data once you get the response, like this:

render : function(){
        var amount = this.state.amount;
        console.log('data', this.state.data);
        ....

Update:

Check the working Code:

var Heading = React.createClass({
    getInitialState: function() {
        return {
          data: [],
          amount : 1000
        };
    },
    handleChange: function(event){
      this.setState({amount : event.target.value});
    },
      loadCommentsFromServer: function() {
        var value = {
          method : 'GET' ,
          headers : {
            'Accept': 'application/json',
            'contentType' : 'application/x-www-form-urlencoded',
          },
          body : ({
            amount : this.state.amount
          })
        };
          fetch('http://localhost:3000/getIOT', value)
          .then((response) => response.json())
          .then((responseData) =>{
            this.setState({data: responseData});
          })
          .catch(function(err){
           console.log(err);
        });
      },
      showTable : function(){
        console.log(this.state.data);
      },
      render : function(){
        var amount = this.state.amount;
        console.log('data', this.state.data);
        return(
          <div className="container">
            <div className="row">
              <div classname="col-xs-4 col-xs-offset-4">
                <div className="text-center">
                  <h1>{this.props.name}</h1>
                  <h2> {amount} </h2>
                  <input type="text" value={amount} onChange={this.handleChange} />
                  <button onClick={this.showTable}>Show Table</button>
                  <button onClick={this.loadCommentsFromServer}> Submit </button>
                </div>
              </div>
            </div>
          </div>
        );
      }
  });
ReactDOM.render(
    <div>
      <Heading
      name="React JS"
      >
      </Heading>
      </div>
  , document.getElementById('reactBinding'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='reactBinding'></div>

Upvotes: 2

Related Questions