Skip to content

Instantly share code, notes, and snippets.

@thomas-lebeau
Created February 8, 2020 12:02
Show Gist options
  • Save thomas-lebeau/6a0d4132f3de4393f90c4dd5f6460845 to your computer and use it in GitHub Desktop.
Save thomas-lebeau/6a0d4132f3de4393f90c4dd5f6460845 to your computer and use it in GitHub Desktop.
Martian photo fetcher
import React, { Component } from "react";
import ReactDOM from "react-dom";
const wait = response =>
new Promise(resolve => setTimeout(() => resolve(response), 3000));
const handleErrors = response => {
if (response.status < 200 || response.status >= 300) {
throw new Error("Network Error");
}
return response;
};
class MartianPhotoFetcher extends Component {
state = {
photos: [],
error: null,
loading: true
};
componentDidMount() {
fetch(
`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=${
this.props.date
}&api_key=gnesiqnKCJMm8UTYZYi86ZA5RAnrO4TAR9gDstVb`
)
.then(wait)
.then(handleErrors)
.then(response => response.json())
.then(data => this.setState({ photos: data.photos, loading: false }))
.catch(error => this.setState({ error, loading: false }));
}
render() {
if (this.state.loading) {
return <span>Loading...</span>;
}
if (this.state.error) {
return <span>❌ Error: {this.state.error.message}</span>;
}
return (
<>
{this.state.photos.map(photo => (
<img src={photo.img_src} alt="" width="100" height="100" />
))}
</>
);
}
}
ReactDOM.render(
<MartianPhotoFetcher date="2019-01-01" />,
document.getElementById("root")
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment