Skip to content

Commit

Permalink
Merge pull request #5 from plangrid/cors
Browse files Browse the repository at this point in the history
adds client-side cors handling
  • Loading branch information
viktoriyavulfson authored May 16, 2017
2 parents 931f81c + cf80fec commit 40de40f
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ import "styles/main.scss";

ReactDOM.render(
<FileViewer fileType="csv"
filePath="http://spatialkeydocs.s3.amazonaws.com/FL_insurance_sample.csv"/>,
filePath="https://data.cityofnewyork.us/api/views/3h6b-pt5u/rows.csv"/>,
document.getElementById('app')
);
30 changes: 22 additions & 8 deletions src/components/fetch-wrapper.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,43 @@ function withFetching(WrappedComponent, props) {
return class extends Component {
constructor(props) {
super(props);
this.state = { data: {} };
this.xhr = this.createRequest()
this.state = {};
this.xhr = this.createRequest(props.filePath)
}

componentDidMount() {
this.fetch(this.props.filePath);
this.fetch();
}

componentWillUnmount() {
this.abort()
}

render() {
if (this.state.data.length > 0 || Object.keys(this.state.data).length > 0) {
if (!this.xhr)
return <h1>CORS not supported..</h1>;

if (this.state.data) {
return <WrappedComponent data={this.state.data} {...this.props} />;
} else {
return <h1>Loading..</h1>
}
}

createRequest() {
const xhr = new XMLHttpRequest();
createRequest(path) {
let xhr = new XMLHttpRequest();

if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open("GET", path, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open("GET", path);
} else {
// CORS not supported.
xhr = null;
}

xhr.onreadystatechange = () => {
if (this.xhr.readyState == 4 && this.xhr.status == 200) {
Expand All @@ -36,8 +51,7 @@ function withFetching(WrappedComponent, props) {
return xhr;
}

fetch(path) {
this.xhr.open("GET", path, true);
fetch() {
this.xhr.send();
}

Expand Down
8 changes: 4 additions & 4 deletions src/components/file-viewer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { CsvViewer } from "./drivers";

class FileViewer extends Component {
render() {
let Driver = this.getDriver(this.props.fileType);
let Driver = this.getDriver(this.props);

return (
<div className='file-viewer'>
Expand All @@ -14,10 +14,10 @@ class FileViewer extends Component {
);
}

getDriver(fileTYpe) {
switch (fileTYpe) {
getDriver(props) {
switch (props.fileType) {
case "csv": {
return withFetching(CsvViewer)
return withFetching(CsvViewer, props)
}
default: {
return <h1>File type is not supported</h1>
Expand Down

0 comments on commit 40de40f

Please sign in to comment.