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.

9
  • 1
    then((response) => response.json()) typo ? Commented Feb 26, 2017 at 17:03
  • 1
    Off topic, but if you're using babel for the JSX, why not also use it to do proper classes instead of the legacy React.createClass? Commented Feb 26, 2017 at 17:03
  • @VladuIonut I fixed the typo, but now I am not getting any information at all.... Commented Feb 26, 2017 at 17:04
  • 1
    @ndugger: 'proper' classes..? Commented Feb 26, 2017 at 17:05
  • 1
    LOL i know you guys want to hear ndugger out, but in the mean time can someone help me ? :D Commented Feb 26, 2017 at 17:08

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

10 Comments

Uncaught ReferenceError: data is not defined :(
first it shows data [ ] <-- empty, then the error pops up if I click the submit
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 :)
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?
check request header in developer tool, if amount value is proper, then your frontend part is ok, otherwise its a frontend issue.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.