0

I am having some trouble in getting fetch return data from my cloud function, I am only trying to write data into google spreadsheet with cloud function for now. Below is my current code so far.

I have a button with onClick={this.AddRecord} which will then call the cloud function

AddRecord = async () => {

    await fetch(url, {
        method: 'POST',
        body: JSON.stringify({
            date: this.getDate(),
            name: this.state.name,
            number: '\'' + this.state.number
        })
    })
    .then((response) => {return response.json()})
    .then((data) => {
        alert(data)         // this never gets executed
        this.setState({message:data})
    })
    .catch((err) => {
        this.setState({message: err})
    });
}

and this is my cloud function POST handler:

case 'POST':
   /* parse the string body into a usable JS object */
   const data = JSON.parse(event.body);

   const addedRow = await sheet.addRow(data);

   return {
      statusCode : 200,
      body: JSON.stringify({
         message : 'Posted successfully.',
         rowNumber: addedRow._rowNumber - 1 // minus the header row
      })
   };

Appreciate it if anyone could point me in the right direction, as I have spent a lot of time trying to debug this but with no avail.

some of the resource that I have read so far:

fetch() call not returning any data

https://www.smashingmagazine.com/2020/06/rest-api-react-fetch-axios/

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Edit:

I have tried to call the cloud function via POSTMAN and successfully gotten a status 200 response with message. POSTMAN testing

So I can safely assume that the issue is not with the cloud function but the fetch function, but I am still clueless on which part of the code went wrong as they seem pretty much the same as other code example that I see online. I will only get TypeError: Failed to fetch when I switch back to POST from my react app. Fetch error

user2232355
  • 195
  • 14
  • check if it is going to `.catch`? – Ashish Nov 04 '20 at 14:06
  • @Ashish, hmm I think you are right. I got an error TypeError: Failed to fetch even I have successfully written to the spreadsheet and gotten a status 200 from cloud function log. To be honest I am not sure what is causing the error now. – user2232355 Nov 04 '20 at 14:17
  • 1
    Please share the exact error message for further help. – Ashish Nov 04 '20 at 14:20
  • Well it only returns TypeError: Failed to fetch, probably similar to this https://stackoverflow.com/questions/49343024/getting-typeerror-failed-to-fetch-when-the-request-hasnt-actually-failed but I am not getting a return response. I then tried to post with POSTMAN and I am successfully getting a response from cloud function, so for now I have no clue on what went wrong in my react app. – user2232355 Nov 06 '20 at 01:55

1 Answers1

0

Change your function to this:

AddRecord = async () => {

    await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type':'application/json' }, // here is the change
        body: JSON.stringify({
            date: this.getDate(),
            name: this.state.name,
            number: '\'' + this.state.number
        })
    })
    .then((response) => response.json())
    .then((data) => {
        alert(data)       
        this.setState({message:data})
    })
    .catch((err) => {
        this.setState({message: err})
    });
}
Cesar
  • 417
  • 5
  • 17
  • I actually started with (response) => response.json() but the result is still the same .then() will not return any data even if I have successfully called the api. Any idea if i have done something wrong ? – user2232355 Nov 04 '20 at 13:45
  • 2
    `.then((response) => {return response.json()})` is same as `.then((response) => response.json())` – Ashish Nov 04 '20 at 14:07
  • Actually, you need to add the JSON header to the call, since fetch by sends `multipart/form-data`. Just updated my answer @user2232355 – Cesar Nov 04 '20 at 14:21
  • Hey man, thanks for your help, but it seems the problem remains after I added the mentioned header. Tried to use POSTMAN to check on the posting and confirmed that the problem is not with the POST function so it must be in AddRecord but I just could not figure it out yet. – user2232355 Nov 06 '20 at 02:02
  • Weird... It looks like you just sent a request with `text`, not `JSON`, if that's the case then you should add those headers. What I'd do is check the headers on the postman request to see what it added as `Content-Type` @user2232355 – Cesar Nov 06 '20 at 11:44