React - superagent request per mapped item

422 views Asked by At

I would like to fire off a superagent request for each item mapped in my search results. To check if the item id is in an array:

I have these methods; one to map the results, and the other a superagent fetch:

renderResultNodes: function () {
    if(!this.props.results) return;

    return this.props.results.map(function (result) {
        // fire off request here?
        // show tick icon if id exists
        var showIcon = this.isSchool(school.id) ? <i className="icon item-icon-right ion-checkmark-circled"></i> : '';

        return (
             <a className="item item-icon-right" key={result.id} href="#"
                data-school-id={result.id}
                data-school-name={result.school_name}
                onClick={this.selectSchool}
                >
                <h2>{result.school_name}</h2>
                <p>{result.s_address1}</p>
                {showIcon}
             </a>
        );
    }.bind(this));
},

// check id exists in json
isSchool: function (schoolId){
    var url = OsaApiService.buildRequestUrl('home', [schoolId]);

    fetch(url)
        .then(function (response) {
            return response.json();
        }).then(function (data) {
            console.log(data);
        }.bind(this)).catch(function (ex) {
            console.log(ex);
        });
},

Can anyone advise if this is the best way to do this? and how I should go about it?

Thanks

1

There are 1 answers

0
Jonny Buchanan On BEST ANSWER

You could use another component for the results to make use of its lifecycle and state:

var Result = React.createClass({
  getInitialState() {
    return {
      isSchool: false 
    }
  },
  componentDidMount() {
    var url = OsaApiService.buildRequestUrl('home', [this.props.id])
    fetch(url)
      .then(response => response.json())
      .then(data => this.setState({isSchool: /* whatever you need from data */}))
      .catch(err => console.log(err))
  },
  render() {
    return <a className="item item-icon-right" onClick={this.props.onClick}>
      <h2>{this.props.school_name}</h2>
      <p>{this.props.s_address1}</p>
      {this.state.isSchool && <i className="icon item-icon-right ion-checkmark-circled"></i>}
    </a>
  }
})

    renderResultNodes: function () {
        if(!this.props.results) return;

        return this.props.results.map(function(result) {
            return <Result key={result.id} onClick={this.selectSchool} {...result}/>
        }, this)
    },