├── .gitignore ├── stories ├── addons.js ├── webpack.config.js ├── config.js └── react-hooks.stories.js ├── rollup.config.js ├── LICENSE ├── .eslintrc.json ├── package.json ├── src ├── react-hooks.ts └── __tests__ │ └── react-hooks.ts ├── tsconfig.json ├── README.md └── jest.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | coverage 4 | .rpt2_cache 5 | npm-debug.log* 6 | yarn-debug.log* 7 | yarn-error.log* 8 | lerna-debug.log* 9 | -------------------------------------------------------------------------------- /stories/addons.js: -------------------------------------------------------------------------------- 1 | import "@storybook/addon-actions/register"; 2 | import "@storybook/addon-links/register"; 3 | import "@storybook/addon-storysource/register"; 4 | -------------------------------------------------------------------------------- /stories/webpack.config.js: -------------------------------------------------------------------------------- 1 | module.exports = function({ config }) { 2 | config.module.rules.push({ 3 | test: /\.stories\.jsx?$/, 4 | loaders: [require.resolve("@storybook/source-loader")], 5 | enforce: "pre", 6 | }); 7 | 8 | return config; 9 | }; 10 | -------------------------------------------------------------------------------- /stories/config.js: -------------------------------------------------------------------------------- 1 | import { configure } from "@storybook/react"; 2 | 3 | // automatically import all files ending in *.stories.js 4 | const req = require.context(".", true, /\.stories\.js$/); 5 | function loadStories() { 6 | req.keys().forEach((filename) => req(filename)); 7 | } 8 | 9 | configure(loadStories, module); 10 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import typescript from "rollup-plugin-typescript2"; 3 | 4 | const root = process.cwd(); 5 | const pkg = require(path.join(root, "package.json")); // eslint-disable-line 6 | 7 | export default { 8 | input: path.join(root, "src/react-hooks.ts"), 9 | output: [ 10 | { 11 | file: pkg.main, 12 | format: "cjs", 13 | sourcemap: true, 14 | }, 15 | { 16 | file: pkg.module, 17 | format: "esm", 18 | sourcemap: true, 19 | }, 20 | ], 21 | plugins: [typescript()], 22 | external: ["react", "@repeaterjs/repeater"], 23 | }; 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 Brian Kim 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "commonjs": true, 5 | "es6": true, 6 | "node": true 7 | }, 8 | "parser": "@typescript-eslint/parser", 9 | "parserOptions": { 10 | "sourceType": "module", 11 | "ecmaFeatures": { 12 | "jsx": true 13 | } 14 | }, 15 | "plugins": [ 16 | "@typescript-eslint", 17 | "jest", 18 | "react", 19 | "react-hooks", 20 | "prettier" 21 | ], 22 | "extends": [ 23 | "eslint:recommended", 24 | "plugin:@typescript-eslint/recommended", 25 | "plugin:jest/recommended", 26 | "plugin:prettier/recommended", 27 | "prettier/@typescript-eslint" 28 | ], 29 | "rules": { 30 | "prettier/prettier": [ 31 | "error", 32 | { 33 | "trailingComma": "all", 34 | "arrowParens": "always" 35 | } 36 | ], 37 | "linebreak-style": ["error", "unix"], 38 | "@typescript-eslint/explicit-function-return-type": 0, 39 | "@typescript-eslint/explicit-member-accessibility": 0, 40 | "@typescript-eslint/no-explicit-any": 0, 41 | "@typescript-eslint/no-object-literal-type-assertion": 0, 42 | "@typescript-eslint/no-non-null-assertion": 0, 43 | "@typescript-eslint/no-parameter-properties": 0, 44 | "@typescript-eslint/no-unused-vars": [ 45 | "error", 46 | { 47 | "argsIgnorePattern": "^_", 48 | "varsIgnorePattern": "^_" 49 | } 50 | ], 51 | "react/prop-types": 0, 52 | "react-hooks/rules-of-hooks": "error", 53 | "react-hooks/exhaustive-deps": "warn" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@repeaterjs/react-hooks", 3 | "version": "0.1.1", 4 | "description": "React hooks for using async iterators in components", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/repeaterjs/repeater", 8 | "directory": "packages/repeater" 9 | }, 10 | "license": "MIT", 11 | "files": [ 12 | "/lib" 13 | ], 14 | "main": "lib/react-hooks.cjs.js", 15 | "module": "lib/react-hooks.esm.js", 16 | "types": "lib/react-hooks.d.ts", 17 | "scripts": { 18 | "prebuild": "yarn run clean", 19 | "build": "rollup -c rollup.config.js", 20 | "clean": "shx rm -rf ./lib", 21 | "lint": "eslint --ignore-path .gitignore --ext .js,.ts,.tsx .", 22 | "prepublishOnly": "yarn run test && yarn run build", 23 | "test": "jest --config jest.config.js --color", 24 | "start-storybook": "start-storybook -p 1337 --config-dir stories", 25 | "build-storybook": "build-storybook --config-dir stories" 26 | }, 27 | "dependencies": { 28 | "@repeaterjs/repeater": "^3.0.1" 29 | }, 30 | "devDependencies": { 31 | "@babel/core": "^7.7.2", 32 | "@storybook/addon-actions": "^5.2.6", 33 | "@storybook/addon-links": "^5.2.6", 34 | "@storybook/addon-storysource": "^5.2.6", 35 | "@storybook/addons": "^5.2.6", 36 | "@storybook/react": "^5.2.6", 37 | "@testing-library/react-hooks": "^3.2.1", 38 | "@types/jest": "^24.0.22", 39 | "@types/react": "^16.9.11", 40 | "@typescript-eslint/eslint-plugin": "^2.6.1", 41 | "@typescript-eslint/parser": "^2.6.1", 42 | "babel-loader": "^8.0.6", 43 | "eslint": "^6.6.0", 44 | "eslint-config-prettier": "^6.5.0", 45 | "eslint-plugin-jest": "^23.0.3", 46 | "eslint-plugin-prettier": "^3.1.1", 47 | "eslint-plugin-react": "^7.16.0", 48 | "eslint-plugin-react-hooks": "^2.2.0", 49 | "jest": "^24.9.0", 50 | "prettier": "^1.19.1", 51 | "react": "^16.11.0", 52 | "react-test-renderer": "^16.11.0", 53 | "rollup": "^1.26.4", 54 | "rollup-plugin-typescript2": "^0.25.2", 55 | "shx": "^0.3.2", 56 | "ts-jest": "^24.1.0", 57 | "typescript": "^3.7.2", 58 | "weak": "^1.0.1" 59 | }, 60 | "peerDependencies": { 61 | "react": "^16.8.0" 62 | }, 63 | "publishConfig": { 64 | "access": "public" 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/react-hooks.ts: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from "react"; 2 | import { Push, Repeater, RepeaterBuffer, Stop } from "@repeaterjs/repeater"; 3 | 4 | // Repeaters are lazy, hooks are eager. 5 | // We need to return push and stop synchronously from the useRepeater hook so 6 | // we prime the repeater by calling next immediately. 7 | function createPrimedRepeater( 8 | buffer?: RepeaterBuffer, 9 | ): [Repeater, Push, Stop] { 10 | let push: Push; 11 | let stop: Stop; 12 | const repeater = new Repeater((push1, stop1) => { 13 | push = push1; 14 | stop = stop1; 15 | // this value is thrown away 16 | push(null as any); 17 | }, buffer); 18 | // pull and throw away the first value so the executor above runs 19 | repeater.next(); 20 | return [repeater, push!, stop!]; 21 | } 22 | 23 | export function useRepeater( 24 | buffer?: RepeaterBuffer, 25 | ): [Repeater, Push, Stop] { 26 | const [tuple] = useState(() => createPrimedRepeater(buffer)); 27 | return tuple; 28 | } 29 | 30 | export function useAsyncIter( 31 | callback: (deps: AsyncIterableIterator) => AsyncIterableIterator, 32 | deps: TDeps = ([] as unknown) as TDeps, 33 | ): AsyncIterableIterator { 34 | const [repeater, push] = useRepeater(); 35 | const [iter] = useState(() => callback(repeater)); 36 | useEffect(() => { 37 | push(deps); 38 | }, [push, ...deps]); // eslint-disable-line react-hooks/exhaustive-deps 39 | 40 | useEffect( 41 | () => () => { 42 | if (iter.return != null) { 43 | // TODO: handle return errors 44 | iter.return().catch(); 45 | } 46 | }, 47 | [iter], 48 | ); 49 | 50 | return iter; 51 | } 52 | 53 | export function useResult( 54 | callback: (deps: AsyncIterableIterator) => AsyncIterableIterator, 55 | deps?: TDeps, 56 | ): IteratorResult | undefined { 57 | const iter = useAsyncIter(callback, deps); 58 | const [result, setResult] = useState>(); 59 | useEffect(() => { 60 | let mounted = true; 61 | (async () => { 62 | try { 63 | while (mounted) { 64 | const result = await iter.next(); 65 | if (mounted) { 66 | setResult(result); 67 | } 68 | 69 | if (result.done) { 70 | break; 71 | } 72 | } 73 | } catch (err) { 74 | if (mounted) { 75 | setResult(() => { 76 | throw err; 77 | }); 78 | } 79 | } 80 | })(); 81 | 82 | return () => { 83 | mounted = false; 84 | }; 85 | }, [iter]); 86 | 87 | return result; 88 | } 89 | 90 | export function useValue( 91 | callback: (deps: AsyncIterableIterator) => AsyncIterableIterator, 92 | deps?: TDeps, 93 | ): T | undefined { 94 | const result = useResult(callback, deps); 95 | return result && result.value; 96 | } 97 | -------------------------------------------------------------------------------- /stories/react-hooks.stories.js: -------------------------------------------------------------------------------- 1 | import React from "react"; // eslint-disable-line 2 | import { useState } from "react"; 3 | import { storiesOf } from "@storybook/react"; 4 | import { Repeater } from "@repeaterjs/repeater"; 5 | import { useAsyncIter, useResult } from "../lib/react-hooks.esm"; 6 | 7 | storiesOf("useResult", module) 8 | .add("counter", () => { 9 | const result = useResult(async function*() { 10 | let i = 0; 11 | while (true) { 12 | yield i++; 13 | await new Promise((resolve) => setTimeout(resolve, 1000)); 14 | } 15 | }); 16 | 17 | return
Current value: {result && result.value}
; 18 | }) 19 | .add("websocket", () => { 20 | const [socket] = useState(() => { 21 | return new WebSocket("wss://echo.websocket.org"); 22 | }); 23 | const [open] = useState(() => { 24 | return new Promise((resolve) => (socket.onopen = resolve)); 25 | }); 26 | const messages = new Repeater(async (push, stop) => { 27 | socket.onmessage = (ev) => push(ev.data); 28 | socket.onerror = () => stop(new Error("WebSocket error")); 29 | socket.onclose = () => stop(); 30 | await stop; 31 | socket.close(); 32 | }); 33 | const [value, setValue] = useState(""); 34 | const result = useResult(async function*() { 35 | const value = []; 36 | yield value; 37 | for await (const message of messages) { 38 | value.push(message); 39 | yield value; 40 | } 41 | }); 42 | return ( 43 |
44 | { 48 | setValue(ev.target.value); 49 | }} 50 | onKeyPress={(ev) => { 51 | if (ev.key === "Enter") { 52 | open.then(() => { 53 | socket.send(value); 54 | setValue(""); 55 | }); 56 | } 57 | }} 58 | /> 59 | {result && 60 | result.value.map((message, i) =>
{message}
)} 61 |
62 | ); 63 | }) 64 | .add("konami", () => { 65 | const konami = [ 66 | "ArrowUp", 67 | "ArrowUp", 68 | "ArrowDown", 69 | "ArrowDown", 70 | "ArrowLeft", 71 | "ArrowRight", 72 | "ArrowLeft", 73 | "ArrowRight", 74 | "b", 75 | "a", 76 | ]; 77 | const keys = useAsyncIter(() => { 78 | return new Repeater(async (push, stop) => { 79 | const listener = (ev) => { 80 | push(ev.key); 81 | }; 82 | window.addEventListener("keyup", listener); 83 | await stop; 84 | window.removeEventListener("keyup", listener); 85 | }); 86 | }); 87 | 88 | const result = useResult(async function*() { 89 | let i = 0; 90 | yield konami[i]; 91 | for await (const key of keys) { 92 | if (key === konami[i]) { 93 | yield `${konami[i]} (pressed)`; 94 | i++; 95 | } else { 96 | i = 0; 97 | } 98 | 99 | if (i < konami.length) { 100 | await new Promise((resolve) => setTimeout(resolve, 100)); 101 | yield konami[i]; 102 | } else { 103 | return "Cheats activated"; 104 | } 105 | } 106 | }); 107 | 108 | if (result == null) { 109 | return null; 110 | } else if (result.done) { 111 | return
🎉 {result.value} 🎉
; 112 | } 113 | 114 | return
Next key: {result.value}
; 115 | }); 116 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/react-hooks.ts" 4 | ], 5 | "compilerOptions": { 6 | /* Basic Options */ 7 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ 8 | // "module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 9 | "lib": ["esnext", "dom"], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | // "outDir": "./lib", /* Redirect output structure to the directory. */ 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "removeComments": true, /* Do not emit comments to output. */ 21 | // "noEmit": true, /* Do not emit outputs. */ 22 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 23 | "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 24 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 25 | 26 | /* Strict Type-Checking Options */ 27 | "strict": true, /* Enable all strict type-checking options. */ 28 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 29 | // "strictNullChecks": true, /* Enable strict null checks. */ 30 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 31 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 32 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 33 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 34 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 35 | 36 | /* Additional Checks */ 37 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 38 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 39 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 40 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 41 | 42 | /* Module Resolution Options */ 43 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 44 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 45 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 46 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 47 | // "typeRoots": [], /* List of folders to include type definitions from. */ 48 | // "types": [], /* Type declaration files to be included in compilation. */ 49 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 50 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 51 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # @repeaterjs/react-hooks 2 | React hooks for working with async iterators/generators. 3 | 4 | These functions are implemented with repeaters. For more information about repeaters, visit [repeater.js.org](https://repeater.js.org). 5 | 6 | ## Installation 7 | ``` 8 | npm install @repeaterjs/react-hooks 9 | ``` 10 | 11 | ``` 12 | yarn add @repeaterjs/react-hooks 13 | ``` 14 | 15 | ## API 16 | ### `useResult` 17 | ```ts 18 | declare function useResult( 19 | callback: (deps: AsyncIterableIterator) => AsyncIterableIterator, 20 | deps?: TDeps, 21 | ): IteratorResult | undefined; 22 | 23 | import {useResult} from "@repeaterjs/react-hooks"; 24 | 25 | const result = useResult(async function *() { 26 | /* ... */ 27 | }); 28 | ``` 29 | 30 | `callback` is a function which returns an async iterator, usually an async generator function. The callback is called when the component initializes and the returned iterator updates the component whenever it produces results. `useResult` returns an `IteratorResult`, an object of type `{value: T, done: boolean}`, where `T` is the type of the produced values, and `done` indicates whether the iterator has returned. The first return value from this hook will be `undefined`, indicating that the iterator has yet to produce any values. 31 | 32 | ```ts 33 | function Timer() { 34 | const result = useResult(async function*() { 35 | let i = 0; 36 | while (true) { 37 | yield i++ 38 | await new Promise((resolve) => setTimeout(resolve, 1000)); 39 | } 40 | }); 41 | 42 | return
Seconds: {result && result.value}
; 43 | } 44 | ``` 45 | 46 | Similar to the `useEffect` hook, `useResult` accepts an array of dependencies as a second argument. However, rather than being referenced via closure, the dependencies are passed into the callback as an async iterator which updates whenever any of the dependencies change. We pass the dependencies in manually because `callback` is only called once, and dependencies referenced via closure become stale as the component updates. 47 | 48 | ```ts 49 | function ProductDetail({productId}) { 50 | const result = useResult(async function *(deps) { 51 | for await (const [productId] of deps) { 52 | const data = await fetchProductData(productId); 53 | yield data.description; 54 | } 55 | }, [productId]); 56 | 57 | if (result == null) { 58 | return
Loading...
; 59 | } 60 | 61 | return
Description: {result.value}
; 62 | } 63 | ``` 64 | 65 | ### `useValue` 66 | ```ts 67 | declare function useValue( 68 | callback: (deps: AsyncIterableIterator) => AsyncIterableIterator, 69 | deps?: TDeps, 70 | ): T | undefined; 71 | 72 | import {useValue} from "@repeaterjs/react-hooks"; 73 | 74 | const value = useValue(async function *() { 75 | /* ... */ 76 | }); 77 | ``` 78 | 79 | Similar to `useResult`, except the `IteratorResult`’s value is returned rather than the `IteratorResult` object itself. Prefer `useValue` over `useResult` when you don’t need to distinguish between whether values were yielded or returned. 80 | 81 | ### `useAsyncIter` 82 | ```ts 83 | declare function useAsyncIter( 84 | callback: (deps: AsyncIterableIterator) => AsyncIterableIterator, 85 | deps: TDeps = ([] as unknown) as TDeps, 86 | ): AsyncIterableIterator; 87 | 88 | import {useAsyncIter} from "@repeaterjs/react-hooks"; 89 | 90 | function MyComponent() { 91 | const iter = useAsyncIter(async function *() { 92 | /* ... */ 93 | }); 94 | /* ... */ 95 | } 96 | ``` 97 | 98 | Similar to `useResult` and `useValue`, except that `useAsyncIter` returns the async iterator itself rather than consuming it. The returned async iterator can be referenced via closure in further `useResult` calls. Prefer `useAsyncIter` over `useResult` or `useValue` when you want to use an async iterator without updating each time a value is produced. 99 | 100 | ```ts 101 | const konami = ["ArrowUp", "ArrowUp", "ArrowDown", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowLeft", "ArrowRight", "b", "a"]; 102 | function Cheats() { 103 | const keys = useAsyncIter(() => { 104 | return new Repeater(async (push, stop) => { 105 | const listener = (ev) => push(ev.key); 106 | window.addEventListener("keyup", listener); 107 | await stop; 108 | window.removeEventListener("keyup", listener); 109 | }); 110 | }); 111 | 112 | const result = useResult(async function *() { 113 | let i = 0; 114 | yield konami[i]; 115 | for await (const key of keys) { 116 | if (key === konami[i]) { 117 | i++; 118 | } else { 119 | i = 0; 120 | } 121 | 122 | if (i < konami.length) { 123 | yield konami[i]; 124 | } else { 125 | return "Cheats activated"; 126 | } 127 | } 128 | }); 129 | 130 | if (result == null) { 131 | return null; 132 | } else if (result.done) { 133 | return
🎉 {result.value} 🎉
; 134 | } 135 | 136 | return
Next key: {result.value}
; 137 | } 138 | ``` 139 | 140 | ### `useRepeater` 141 | ```ts 142 | declare function useRepeater( 143 | buffer?: RepeaterBuffer, 144 | ): [Repeater, Push, Stop]; 145 | 146 | import { useRepeater } from "@repeaterjs/react-hooks"; 147 | import { SlidingBuffer } from "@repeaterjs/repeater"; 148 | 149 | function MyComponent() { 150 | const [repeater, push, stop] = useRepeater(new SlidingBuffer(10)); 151 | /* ... */ 152 | } 153 | ``` 154 | 155 | Creates a repeater which can be used in useResult callbacks. `push` and `stop` 156 | can be used in later callbacks to update the repeater. For more information about 157 | the `push` and `stop` functions or the `buffer` argument, refer to the 158 | [repeater.js docs](https://repeater.js.org/docs/overview). 159 | 160 | ```ts 161 | function MarkdownEditor() { 162 | const [inputs, push] = useRepeater(); 163 | const result = useResult(async function*() { 164 | const md = new Remarkable(); 165 | for await (const input of inputs) { 166 | yield md.render(input); 167 | } 168 | }); 169 | return ( 170 |
171 |

Input

172 |