Created
March 2, 2019 16:12
-
-
Save lenkan/055bfe039045ad17389249955dc1d6f4 to your computer and use it in GitHub Desktop.
React hook get state from an iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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