Reputation: 35
I have a react / redux / node express app that manages patient information. I have a bug with reading new data after I've deleted a patient encounter. The functions work fine until I delete the last encounter associated with the patient. Then there's an error: "Uncaught (in promise) SyntaxError: Unexpected end of JSON input."
To get around having no data passed along, I've tried to check if a 204 status comes back (no content) and I create an empty array and send that along as my JSON response instead of no data. This hasn't fixed the error.
How can I handle the lack of content without an error being raised in the console? Instead of returning [ ] (empty array) I've also tried returning ' [ ] ' (empty array with single quotes around it) (which I thought was valid JSON), but no luck.
readPatientEncounters(id) {
let url = '/encounters/findPatient/'+id;
Data.readData(url,(response) => {
if (response.length !== 0) {
response.sort(function (a, b) {
return a.date-b.date;
});
}
this.props.dispatch(EncountersActions.readEncounters(response));
}, (errorMessage) => {
console.log('having an error>',errorMessage);
});
}
class Data {
static readData(path, onSuccess, onFailure) {
let headers = new Headers({ 'Content-Type': 'application/json',
'x-access-token': sessionStorage.getItem('jwt') });
let myInit = {
'method': 'GET',
'headers': headers
};
let url = config.server_url + path;
fetch(url, myInit).then(response => {
var jsonResponse = response.json();
if (response.status === 204) {
return [];
} else {
return jsonResponse;
}
}).then(jsonResponse => {
onSuccess(jsonResponse);
return;
}).catch(errorMessage => {
onFailure(errorMessage);
return errorMessage;
});
}
}
Upvotes: 0
Views: 910
Reputation: 35
The solution was provided by jaromanda-x (https://stackoverflow.com/users/5053002/jaromanda-x)
This code was converting to JSON format regardless of the response:
var jsonResponse = response.json();
if (response.status === 204) {
return [];
} else {
return jsonResponse;
}
This solved this issue:
if (response.status === 204) {
return [];
} else {
return response.json();
}
Upvotes: 2