Skip to content Skip to sidebar Skip to footer

Render Method, Meteor React

After following the getting started tutorial on the meteor website i stopped around the item '2.4 Create App component', first install: meteor add http The app purpose is to visua

Solution 1:

I don't think its a good idea to call the functions that makes an API call in the render function as it will be called everytime the component renders, a better place will be to have it in the componentDidMount function and save the result in state. If you want the call to repeat, do it in setInterval function like

exportdefaultclassAppextendsComponent {
  state = {data: []}
  componentDidMount() {
    var comp = [...this.state.comp]
    this.interval = setInterval(()=> {
      HTTP.get(apiUrl, {}, function(err, res){
        if(err){
            console.log('ERROR @ CALL');
        } else {
            console.log(res);
            this.setState({data: res.data.data.slice(-50)})

        }
        }.bind(this)); 
     }, 2000)

  }
  componentWillUnmount() {
       clearInterval(this.interval)
  }
  render() {
    return (
      <divclassName="container"><header><h1>Numbers</h1></header><ul>
          {this.state.data.map((result, index) => 
             <likey={result[0] }>{`${result[8]} - ${result[9]}`}</li>
            ); }
        </ul></div>
    );
  }
}

Solution 2:

Final code.

importReact, { Component } from'react';
import { HTTP } from'meteor/http';

var apiUrl = 'https://data.ny.gov/api/views/dg63-4siq/rows.json';

exportdefaultclassAppextendsComponent {
  constructor(props){
      super(props);
      this.state = { data : [] }; 
  }
  componentDidMount(){
      var self = this;
          HTTP.get(apiUrl, {}, function(err, res){
              if(err){
                  console.log('ERROR @ CALL');
                  } else {
                      self.setState((state, props) => ({
                          data : res.data.data.slice(-50)
                          }));
                      console.log("state equals response");
                  }
          });
  }

  render() {
    return (
      <divclassName="container"><header><h1>Numbers</h1></header><ul>
          {this.state.data.map((result) => 
             <likey={result[0] }>{`${result[8]} - ${result[9].split(' ')}`}</li>
            )}
        </ul></div>
    );
  }
}

Post a Comment for "Render Method, Meteor React"