I'm attempting to crack this particular nut where my state isn't updating.
I've got a function calling the NASA api through Axios which is working fine. Currently the datePicked state is empty by default which means the GET request defaults to the current date. I'm to adding functionality to generate a random date (function onRandomDateClick), which is all working fine.
Then I want to update the state of datePicked with the generated date, and then run the onImageGet function which holds the axios request.
Initial State
class Photo extends Component {
state = {
apiUrl: 'XXXXXXXX',
apiKey: 'XXXXXXXX',
image: null,
imgChecked: false,
datePicked: ""
};
Generates random Date, logs variable and state. State currently displays blank. this.setState isn't working.
onRandomDateClick = (e) => {
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
let randomDateResult = randomDate(new Date(2012, 0, 1), new Date())
let datePicked = randomDateResult.toISOString().slice(0,10);
this.setState({datePicked})
console.log("variable is " + datePicked);
console.log("state is " + this.state.datePicked);
this.onImageGet();
}
Axios call with state here
onImageGet = e => {
axios.get(`${this.state.apiUrl}?api_key=${this.state.apiKey}&date=${this.state.datePicked}`)
//response always starts res.data
.then(res => {
const image = res.data;
this.setState({ image })
})
this.setState({imgChecked: true})
}
render() {
...blah blah...
return (
<div className="photo">
... blah blah blah ...
</div>
);
}
}
this.setState({parameter: value})would be the correct syntax.