Hi, I wont to make an app which fetch some pics of NASA image of the day.I show the today’s pic and some (4 for example) previous.I use datepicker to choose the image of the day of date by my choice .The problem is sometimes it work fine, sometimes shows only the today’s photo, sometimes today’s plus one or two previous.Can someone explain what’s going on ?
App.js
import React, { Component } from "react";
import DateInput from "./components/DateInput.js";
import Photo from "./components/Photo.js";
import Axios from "axios";
class App extends Component {
state = {
date: new Date(),
currentPhoto: "",
photos:[]
};
componentDidMount(){
Axios
.get(`https://api.nasa.gov/planetary/apod?&api_key=DEMO_KEY`)
.then(response => this.setState({currentPhoto: response.data}));
this.getImages(5);
}
getImages = n => {
const daysBuffer = [];
for(let i=1; i<n; i++){
let today = new Date();
today.setDate(today.getDate()-i);
daysBuffer.push(today);
}
const picBuffer = [];
const datesBuffer = daysBuffer.map(day => this.getDate(day));
datesBuffer.map(date => {
Axios
.get(`https://api.nasa.gov/planetary/apod?date=${date}&api_key=DEMO_KEY`)
.then(response => picBuffer.push(response.data));
})
this.setState({photos: picBuffer});
}
getDate = time => {
let year = time.getFullYear();
let month = time.getMonth();
let day = time.getDate();
return (
`${year}-${month}-${day}`
)
};
getPhoto = a => {
let date = this.getDate(a);
Axios
.get(`https://api.nasa.gov/planetary/apod?date=${date}&api_key=DEMO_KEY`)
.then(response => this.setState({currentPhoto: response.data}))
}
changeDate = date => {
this.setState({
date
});
this.getPhoto(date);
}
render() {
const imageGrid = this.state.photos.map(pic => {
return (
<ul>
<Photo photo = {pic} key={pic.date} />
</ul>
)
})
return (
<div>
<h1>NASA's Astronomy Picture of the Day</h1>
<DateInput
changeDate = {this.changeDate}
date = {this.state.date}
/>
<Photo photo = {this.state.currentPhoto} />
{imageGrid}
</div>
);
}
}
export default App;
DateInput.js
import React from "react";
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
const DateInput = props => (
<div>
Select a Date:
<DatePicker
selected = {props.date}
onChange = {props.changeDate}
/>
</div>
);
export default DateInput;
Photo.js
import React from 'react';
const Photo = props => (
<div>
<h3>{props.photo.title}</h3>
<img src={props.photo.url} alt={props.photo.title} />
<p>{props.photo.explanation}</p>
</div>
)
export default Photo;