I send request to api, I setState with that data only when I got received data back from api, else I setState to undefined. But sometimes those data comes back empty (those data are like that), so in that case I setState to undefined. Works OK, except when i have no input and try to send request, then I get "Unhandled Rejection (SyntaxError): Unexpected end of JSON input" Since I setState to undefined everytime except when I get data from api, why is this happening?
Tried to wrap it with try/catch to see an error, but it did not even started. Then I checked for typos etc. Also tried to wrap that whole if statement to another one, where it would run only when received data from api is true, but it didnt do anything.
getPictureFunc = async event => {
event.preventDefault();
//here i grab values from user input in Form.js
const year = event.target.elements.year.value;
const month = event.target.elements.month.value;
const day = event.target.elements.day.value;
//here i make request call to NASA's API:
const api_call = await fetch(
`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?
earth_date=${year}-
${month}-${day}&api_key=${API_KEY}`
);
//here i save received data to JSON:
const receivedDataFromApi = await api_call.json();
if (year && month && day) {
console.log(receivedDataFromApi);
this.setState({
sol: receivedDataFromApi.photos[0].sol,
earth_date: receivedDataFromApi.photos[0].earth_date,
img: receivedDataFromApi.photos[0].img_src,
error: ""
});
} else {
this.setState({
sol: undefined,
earth_date: undefined,
img: undefined,
error: "no pics for this day, try another one"
});
}
};