- Oct 2023
- Mar 2023
-
github.com github.com
-
jakearchibald.com jakearchibald.com
Tags
Annotators
URL
-
-
-
```js import React, { Component } from 'react'; import './style.css'; import ndjsonStream from 'can-ndjson-stream';
class App extends Component { constructor(props) { super(props);
this.state = { todos: [] };
}
componentDidMount(){ fetch('http://localhost:5000/api/10', { method: 'get' }).then(data => { return ndjsonStream(data.body); }).then((todoStream) => { const streamReader = todoStream.getReader(); const read = result => { if (result.done) return;
this.setState({ todos: this.state.todos.concat([result.value.user]) }); streamReader.read().then(read); }; streamReader.read().then(read); }).catch(err => { console.error(err) });
}
render() { return ( <div className="App">
React + NDJSON Stream Demo
-
{this.state.todos.map((todo, i) =>
- {todo} )}
export default App; ```
-
-
andreitopli.medium.com andreitopli.medium.com
-
Tags
Annotators
URL
-
-
dataprotocols.org dataprotocols.org
Tags
Annotators
URL
-
- Feb 2023
-
ndjson.org ndjson.orgndjson1
Tags
Annotators
URL
-
-
deanhume.com deanhume.com
-
```js /* * Fetch and process the stream / async function process() { // Retrieve NDJSON from the server const response = await fetch('http://localhost:3000/request');
const results = response.body // From bytes to text: .pipeThrough(new TextDecoderStream()) // Buffer until newlines: .pipeThrough(splitStream('\n')) // Parse chunks as JSON: .pipeThrough(parseJSON());
// Loop through the results and write to the DOM writeToDOM(results.getReader()); }
/* * Read through the results and write to the DOM * @param {object} reader / function writeToDOM(reader) { reader.read().then(({ value, done }) => { if (done) { console.log("The stream was already closed!");
} else { // Build up the values let result = document.createElement('div'); result.innerHTML = `<div>ID: ${value.id} - Phone: ${value.phone} - Result: $ {value.result}</div><br>`; // Prepend to the target targetDiv.insertBefore(result, targetDiv.firstChild); // Recursively call writeToDOM(reader); }
}, e => console.error("The stream became errored and cannot be read from!", e) ); } ```
Tags
Annotators
URL
-
- Jul 2021
-
github.com github.com
Tags
Annotators
URL
-