Utilizing the fetch method for API calls that provide JSON data.
Sometimes, the response from the API call includes a status of OK
but with a content value of null
. Initially, I relied on solely checking the status for content which led to errors when there was no actual JSON data present.
The error message I encountered is:
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
My current fetch pattern requires adjustment to incorporate an additional check for the presence of JSON data. What modifications should be made?
export const getSomeData = () => {
return (dispatch) => fetch('/api/myapifunction', fetchOptionsGet())
.then((response) => {
if(response.ok) {
// Additional logic needed here to verify JSON data before calling parseJSON
parseJSON(response)
.then(data => {
// Perform desired actions
})
} else {
// Request failed
// Error handling
}
})
}
I have implemented separate functions like fetch options for GET or POST requests and parseJSON. These are basic utility functions. Here is how parseJSON function is defined:
export const parseJSON = (response) => {
return response.json();
}
It appears that response.json() simply returns a promise, not raw data. How can I validate the presence of JSON data in the response?