Skip to content

Instantly share code, notes, and snippets.

@didacus
Last active July 15, 2017 14:08
Show Gist options
  • Save didacus/c674046632f05cf79500de4df9584b7d to your computer and use it in GitHub Desktop.
Save didacus/c674046632f05cf79500de4df9584b7d to your computer and use it in GitHub Desktop.
How to use fetch
import React, { Component } from 'react'; //import 'React' default export, and { Component } non-default export from react
import fetch from 'isomorphic-fetch'; // isomorphic-fetch is used for both server side and client side 'fetch' (see https://github.com/matthew-andrews/isomorphic-fetch)
// App.css was a hangover from the create-react-app, it's not really needed for this basic example
const url = 'https://api.tfl.gov.uk/BikePoint'; // API
class App extends Component { // This is the same as 'extends 'React.Component'
constructor(props) {
super(props);
this.state = {
fetchedData: null // stores the result of the fetch response body converted to a javascript object
};
}
fetchIt = () => {
console.log('fetching it');
fetch(url, { mode: 'cors' }) // Make sure fetch is cross-origin, it's not by default (see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) since the target URL of the API is a different 'origin' to our react app
.then((resp) => {
console.log(resp);
return resp.json(); })
.then((data) => { // data input parameter is the result of the resolved resp.json() Promise (see https://developer.mozilla.org/en-US/docs/Web/API/Body/json)
console.log(data);
this.setState({ fetchedData: data }); // setState sets the component state with the data from the API response
})
.catch(function(error) {
console.log(JSON.stringify(error));
});
}
render() {
if(!this.state.fetchedData){ // only do the fetch if there is no fetchedData already (BTW this will run many times if the API is unavailable, or 'fetchIt() encounters an error)
this.fetchIt();
}
return (
<div>
{
this.state.fetchedData ? `fetched ${this.state.fetchedData.length} entries` : 'no data' // This is a 'ternary' expression, a simple 'if->else'
/* equivalent to:
if(this.state.fetchedData) {
return `fetched ${this.state.fetchedData.length} entries`; // this is 'javascript string interpolation'
} else {
return 'no data';
}
*
* */
}
</div>
);
}
}
export default App; // Export our component to be used by other react higher order components (parents), in this case, it's imported in 'index.js', data is only fetched when the component renders.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment