Ajax
In previous parts we have created react functioning application that consists from 3 components, which can communicate and respond to events, but what kind of app is this if it only displaying some static data?
Of course we need to do to some server request for bring some real data.
Unlike angular that has its own http service, react doesn't have helper functions for ajax and this due to its convention - to be lighter as possible.
Fot quickly write a code that makes ajax request we will use good old jquery library. Instead of build some server for serve us data we will take an advantage of awesome github api
For example following api will get you repositories those names contains some characters you specified as search param:
var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
$.get(url, function (result) {
//result.items will contain repositories corresponding to query
})
Make a Request
Now the only thing left is to get the request to play with the other code:
//Search Page
var SearchPage = React.createClass({
getInitialState: function() {
return {results: [{text:'some result'}]};
},
loadResults: function(query){
var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
$.get(url, function (result) {
if(result.items.length!==0){
var results = result.items.map(item => {
return {text: item.name};//<--- for our app we need each item to have "text" property
}).slice(0,5);
this.setState({results:results});
}
}.bind(this));//<-- important to bind this for use "setState"
},
handleSearchTextChange: function(txt){
this.loadResults(txt)//<--- calling the request with search term passed from search input
},
render: function() {
return (
<div>
<SearchBar onTextChange={this.handleSearchTextChange}/>
<ResultsList results={this.state.results} />
</div>
);
}
});
Note that for pass the results to ResultsList component we need only to modify the state
using the setState method.view the code
Hope you have fun reading