11 Matching Annotations
  1. Oct 2023
  2. Mar 2023
    1. ```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}
      • )}
      </div> ); } }

      export default App; ```

  3. Feb 2023
    1. ```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) ); } ```

  4. Jul 2021