0

I want to avoid typing the same lines of code. Currently, I have an app that is supposed to make an API call, like so.

render: function(){
  var processappkey = localStorage.getItem('yourid');
  var weather = new XMLHttpRequest();
  var deesfault = "Houston, Texas";
  weather.open("GET", "http://apidatafromsomewebsiteq="+deesfault+"&units=imperial&appid="+processappkey, false);
  weather.send(null);   
  var r = JSON.parse(weather.response);
  var check = r.main.temp;
  var theunicorn = r.weather[0].icon;

  return (<p>{theunicorn}</p>)
}

I would like to split this up to something like this:

somecontainer: function(){
  var processappkey = localStorage.getItem('yourid');
  var weather = new XMLHttpRequest();
  var deesfault = "Houston, Texas";
  weather.open("GET", "http://apidatafromsomewebsiteq="+deesfault+"&units=imperial&appid="+processappkey, false);
  weather.send(null);   
  var r = JSON.parse(weather.response);
  var check = r.main.temp;
  var theunicorn = r.weather[0].icon;
},

render: function() {
   {this.somecontainer()}

   return (
     <p>{theunicorn}</p>
   )
}

I will be calling the API from different areas in my app. Not to mention including a setInverval, which will have me repeating the code again.

As a matter of fact, while I am at it I would also like to know how to go about something like this.

render: function() {
  this.somecontainer();
  setInterval(function() {
    this.somecontainer();
  }, 5000);
}

However, that is a different question, and I'll be happy for insight on the first issue.

3
  • 1
    Why don't you just return theunicorn from within this.samecontainer? Commented Jul 17, 2016 at 22:00
  • Point taken. That would def be the right way to go about it. EDIT. hang on. The goal is to return different things, while calling from the same source. Apologies. This def wasn't made clear in the post. Being said, I do not believe this would necessarily solve things. Commented Jul 17, 2016 at 22:10
  • 1
    If the goal is to return different things(values), I would suggest you to wrap the values into an object and return that object . And access it in the render method by Object,key Commented Jul 17, 2016 at 23:43

1 Answer 1

1

Good question, pretty easy answer. Just have a function that goes and gets the data you want, and returns the result via a callback function. This utility function would sit in another file somewhere and you can import it and call it from any component. Then, take the data that the function returns and put it in your components state.

You should almost certainly not be calling an API in the render method. React can run the render() method a lot depending on your app. If you want it to fire when the component first loads, use componentDidMount (this will only fire on the client, handy if you're using server-side rendering).

let counter = 0;
// separate utility

function goGetAUnicorn(callback) {
  // replicate async for demonstration...
  setTimeout(() => {
    callback(`I am unicorn picture #${counter++}`);
  }, 100)
}

class Unicorn extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      unicornPicture: '',
    };
  }

  componentDidMount() {
    // runs once, client side only
     goGetAUnicorn(unicornPicture => {
       this.setState({unicornPicture});
     });


    // to simulate reusing the same function elsewhere at some other time
    setInterval(() => {
      goGetAUnicorn(unicornPicture => {
        this.setState({unicornPicture});
      });
    }, 1000)
  }

  render() {
    return (
      <div>Here is your unicorn: {this.state.unicornPicture}</div>
    );
  }
}

ReactDOM.render(<Unicorn />, document.getElementById('app'));

I'm using setTimeout just to indicate that you must wait for the response before carrying on. I'd actually use a promise, not a callback, but they both work.

Here's a jsbin to play with: https://jsbin.com/lohojo/1/edit?html,js,output

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

Comments

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.