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.
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.