React fetch data
minimal example
by jonahe
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
const FAKE_DATA = {
locationName: "Göteborg",
locationTemp: "18 deg C"
};
// this simulates getting data from an API where it takes time to fetch.
function getFakeDataAfterMs(msToWait) {
return new Promise((resolve) => setTimeout(() => resolve(FAKE_DATA), msToWait));
}
class WeatherApp extends React.Component {
// this method with be run when the component is created. Here we "initialize" the internal component state
constructor(props) {
super(props);
this.state = {
data: null // data not fetched yet. set default value
}
}
// this method will run when the component has been "attached" to the DOM. ..ish
componentDidMount() {
// fetch data
getFakeDataAfterMs(2000).then(data => {
// when we have the data, put it into the component internal state.
this.setState({data: data});
});
}
// this method decides what to "render" to the DOM.
// It will "re-run" everytime a prop (this.props) or an internal state (this.state) changes
render() {
const {data} = this.state;
// pick out the "data" property from state.
// if we don't have data (data is false by default, see constructor above) then show Loading message
if(!this.state.data) return <div>Waiting for data..</div>;
// If we get to this line, we have data! pick out the properties we want from data and render them
const {locationName, locationTemp} = data;
return (
<div>
<h1>{locationName}</h1>
<h3>{locationTemp}</h3>
</div>
)
}
}
ReactDOM.render(<WeatherApp />, document.querySelector("#app"))