I’m trying to handle a streamed response from an API using Axios, and I need help in figuring out how to parse the streamed data into JSON chunks. I came across this code, but it’s not mine, and I’m trying to understand how others might solve this problem or approach a similar situation.
Here’s the code for reference:
<code> const res = await axiosInstance.get('/products', { responseType: 'stream' });
return res.data
.split('data:')
.map((dataChunk: string) => {
try {
if (dataChunk == '') return null;
return JSON.parse(dataChunk);
} catch (err) {
console.error('Could not parse JSON: ' + err);
}
})
.filter((data?: JSON) => data !== null);
}
</code>
<code> const res = await axiosInstance.get('/products', { responseType: 'stream' });
return res.data
.split('data:')
.map((dataChunk: string) => {
try {
if (dataChunk == '') return null;
return JSON.parse(dataChunk);
} catch (err) {
console.error('Could not parse JSON: ' + err);
}
})
.filter((data?: JSON) => data !== null);
}
</code>
const res = await axiosInstance.get('/products', { responseType: 'stream' });
return res.data
.split('data:')
.map((dataChunk: string) => {
try {
if (dataChunk == '') return null;
return JSON.parse(dataChunk);
} catch (err) {
console.error('Could not parse JSON: ' + err);
}
})
.filter((data?: JSON) => data !== null);
}