In the following
const fetchData = async () => {
try {
const response = await fetch("faulty-endpoint");
const data = await response.text()
console.log('data', data)
} catch (error) {
console.error(error)
} finally {
setLoading(false)
}
}
How do I turn the response.text() data back to json? I can't do
const data = await response.json()
Because then I console.log nothing. I want it to be JSON format so I can save it into a useState array that I can map across.
Because of that trailing comma, you can remove it first, then use JSON.parse:
let text = await response.text();
// if trailing comma present, remove last character by slicing it off
// -1 in slice is the same as text.length - 1
if (text.endsWith(",")) text = text.slice(0, -1);
const data = JSON.parse(text);
This isn't the best or cleanest solution however; ideally the API should return valid JSON...
Here's a working proof-of-concept implementation of youdateme's answer.
I'm faking the request here to avoid CORS issues and such, but the response is copied from the endpoint in your question.
(Note: I had to re-escape the quotes around \"Hello World\" in the last record in the exported template string.)
It does what youdateme suggested and it works.
const fetchData = async () => {
try {
const response = await fakeRequest();
const data = JSON.parse(response.replace(/,$/, ""));
setData(data);
} catch (error) {
console.error(error);
}
};
fetchData();
If this solves your problem you should accept youdateme's answer.
JSON and a JavaScript object look similar, but they're different. JSON is only a string that's formatted like a JavaScript object. See: Working with JSON - MDN
To map across, you need it to be a JavaScript object, not JSON.
Use JSON.parse(yourResponse) to parse a JSON string into a JavaScript object (or array, etc.). See: JSON.parse from MDN
To convert a JavaScript object into a JSON string, you may use JSON.stringify(yourObject)