javascript / expert
Snippet
Async Generator Stream Processing into Array State Buffers
Combining asynchronous generator functions (`async function*`) with `for await...of` loops enables non-blocking streaming of data directly into React array buffers. Yielded string arrays are progressively merged into state while preserving cleanup flag guards against race conditions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React, { useState, useEffect } from 'react';async function* fetchChunkStream(url) {const response = await fetch(url);const reader = response.body.getReader();const decoder = new TextDecoder();while (true) {const { done, value } = await reader.read();if (done) break;yield decoder.decode(value).trim().split('\n');}}export function StreamDataViewer({ endpoint }) {const [dataLines, setDataLines] = useState([]);useEffect(() => {let active = true;async function consumeStream() {for await (const chunkArray of fetchChunkStream(endpoint)) {if (!active) break;setDataLines(prev => prev.concat(chunkArray));}}consumeStream();return () => { active = false; };}, [endpoint]);return <ul>{dataLines.map((line, i) => <li key={i}>{line}</li>)}</ul>;}
react
Breakdown
1
async function* fetchChunkStream(url) {
Defines an asynchronous generator function yielding arrays of decoded strings as chunks arrive from ReadableStream.
2
for await (const chunkArray of fetchChunkStream(endpoint)) {
Iterates asynchronously over each emitted array chunk yielded by the generator stream.
3
setDataLines(prev => prev.concat(chunkArray));
Appends new incoming array items to existing array state using immutable concat calls.