0
votes

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"
      });
    }
  };
2

2 Answers

0
votes

Fetch calls returns promises so you don't necessarily need to use await, instead you could do the following:

fetch(https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photosearth_date=${year}-${month}-${day}&api_key=${API_KEY}`)
.then(res => res.json())
.then(parsedRes => {
    if(year && month && day){
        this.setState({
        sol: parsedRes.photos[0].sol,
        earth_date: parsedRes.photos[0].earth_date,
        img: parsedRes.photos[0].img_src,
        error: ""
        });
    } else {
       this.setState({
       sol: undefined,
       earth_date: undefined,
       img: undefined,
       error: "no pics for this day, try another one"
       }); 
    }
})
.catch(err => {
    console.log(err)
});

Hope it could helps.

0
votes

Your issue is that when your parameters are empty, the call doesn't return "empty data", but actually fails. And you are expecting it to be JSON.

So, you are getting back "Unhandled Rejection (SyntaxError): Unexpected end of JSON input" because it's telling you that you think this is JSON (and calling api_call.json() on it), but the response from the NASA server is not JSON in this case.