Reputation: 1512
I am new to React, and in my very simple app, I am just trying to read and display a json data (of Companies and jobs they have posted). Using React 16.3.0 and react-dom 16.3.2 and axios 0.18.0
My code is below and the final output should show the data I am trying to fetch in each row in a nice format.
But its not rendering at all and getting error - I must be doing some very stupid mistake here.
Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined
at isURLSameOrigin (isURLSameOrigin.js:57)
at dispatchXhrRequest (xhr.js:109)
at new Promise (<anonymous>)
at xhrAdapter (xhr.js:12)
at dispatchRequest (dispatchRequest.js:59)
Here's my code and here's my jsfiddle
<!-- DOCTYPE HTML -->
<html>
<head>
<title>Your First React Project</title>
<link rel="stylesheet" type="text/css" href="app.css">
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class App extends React.component {
constructor (props) {
super(props);
this.state = { jobs: [] };
}
componentDidMount () {
// var th = this;
this.serverRequest =
axios.get(this.props.source)
.then(function(result) {
this.setState({
jobs: result.data.jobs
});
})
}
componentWillUnmount () {
this.serverRequest.abort();
}
render () {
return (
<div>
<h1>Jobs!</h1>
{/* Don't have an ID to use for the key, URL work ok? */}
{this.state.jobs.map(function(job) {
return (
<div key={job.url} className="job">
<a href={job.url}>
{job.company_name}
is looking for a
{job.term}
{job.title}
</a>
</div>
);
})}
</div>
)
}
}
ReactDOM.render(<App source="https://gist.githubusercontent.com/rohan-paul/b74bf6ef1adfdb92e0af5783e6c93a71/raw/bdffbbcb50128c03dd9edc90dbeb85e88c70ebc4/jobs.json"/>, document.getElementById('#root'));
</script>
</body>
</html>
Upvotes: 0
Views: 2964
Reputation: 355
Here's fixed jsfiddle: https://jsfiddle.net/n85v504b/2/
The problem is you're making cross origin request which is not allowed by default. I've changed the axios call to:
axios.request({
method: "get",
url: this.props.source,
crossDomain: true
})
Also changed the promise fullfillment since this was undefined (reason explained here Why is "this" in an anonymous function undefined when using strict?)
then((result) => this.setState({jobs: result.data.jobs}))
Upvotes: 2