I am trying to make a Wikipedia Viewer with React. But, I cannot make a normal ajax call to get data from Wikipedia API on my localhost due to cross origin issue. React also does not seem to accept jquery ($) for me to use jquery JSON-p. I also tried pure javascript way, but I am not sure if I was doing wrong way, it did not work either.
Could anyone tell me how I can make JSON-p call from react component to Wikipedia API?
Here is the jquery JSOP api call I used.
require jquery from 'jquery';
$.when($.ajax({ url: "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&redirects=return&search="+searchTerm, dataType: 'jsonp' })) .then(function(result){ ...
UPDATE: Now I got jquery working in react. I used - import $ from 'jquery'. API call seems to be working. But, I cannot take the data out of the jquery json-p block. It does not recognize this.setState or any other function which is outside of this block. Below is my code so far:
import $ from 'jquery';
import React from 'react';
import { render } from 'react-dom';
import Searchbar from './Searchbar';
import ListView from './ListView';
class App extends React.Component {
constructor(){
super();
this.state = {
term: ""
};
}
searchWiki(term){
$.when($.ajax({
url: "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&redirects=return&search="+term,
dataType: 'jsonp'
}))
.then(function(result){
console.log(result);
this.setState({term:term});
});
}
render(){
return(
<div>
<center>
<h1>Wikipedia Viewer</h1>
<Searchbar onSearchTermChange={this.searchWiki.bind(this)}/>
<ListView term={this.state.term}/>
</center>
</div>
)
}
}
render(<App />, document.getElementById('app'))