0

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.

Masnad Nihit
  • 1,986
  • 2
  • 21
  • 40

1 Answers1

2

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>
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
  • Uncaught ReferenceError: data is not defined :( – Masnad Nihit Feb 26 '17 at 17:10
  • first it shows data [ ] <-- empty, then the error pops up if I click the submit – Masnad Nihit Feb 26 '17 at 17:12
  • you are getting that error because use used `console.log(data)` in `showTable` method, instead of that use `console.log(this.state.data)`, check the working code :) – Mayank Shukla Feb 26 '17 at 17:28
  • It works! Thanks!!, One issue though, even though its not part of the problem, when I use fetch and try to send the amount as a get request, my node js server does not receive it .... Got any idea what I am doing wrong? – Masnad Nihit Feb 26 '17 at 17:31
  • check request header in developer tool, if amount value is proper, then your `frontend` part is ok, otherwise its a `frontend` issue. – Mayank Shukla Feb 26 '17 at 17:37
  • The developer tool shows that there is no information getting passed. – Masnad Nihit Feb 26 '17 at 17:43
  • check this one: http://stackoverflow.com/questions/29775797/fetch-post-json-data, may be helpful :) – Mayank Shukla Feb 26 '17 at 17:46
  • is it working ? i never used fetch so don't have much idea about it :) – Mayank Shukla Feb 26 '17 at 17:50
  • No dint use the link, I just added the amount to the URL instead ;) This is the first time I am writing with react.js and using fetch so I am just doing it the old fashioned way :D Need to learn a bit more to get writing proper codes for react :D – Masnad Nihit Feb 26 '17 at 17:52
  • start your journey from this place: https://facebook.github.io/react/docs/hello-world.html it will help you alot :) – Mayank Shukla Feb 26 '17 at 17:54