Fetch API & Handling JSON Responses
What type of API interaction does this code handle?
const response = await fetch('/api/stream', {
headers: {
'Accept': 'text/event-stream'
}
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const {done, value} = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const events = chunk.split('\n\n');
for (const event of events) {
if (event.trim()) {
const data = JSON.parse(event.replace('data: ', ''));
console.log(data);
}
}
}