Skip to content

Instantly share code, notes, and snippets.

@lenkan
Created March 2, 2019 16:12
Show Gist options
  • Save lenkan/055bfe039045ad17389249955dc1d6f4 to your computer and use it in GitHub Desktop.
Save lenkan/055bfe039045ad17389249955dc1d6f4 to your computer and use it in GitHub Desktop.
React hook get state from an iterator
// @ts-check
import { useState, useEffect } from 'react'
/**
* @param {() => AsyncIterableIterator<T>} iterator
* @param {T} [defaultValue]
* @returns {T}
* @template T
*/
export function useIterator (iterator, defaultValue) {
const [state, setState] = useState(defaultValue)
async function start () {
for await (const next of iterator()) {
setState({ ...state, ...next })
}
}
useEffect(() => { start() }, [])
return state
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment