├── .eslintrc.json ├── .gitignore ├── LICENSE ├── README.md ├── jest.config.js ├── package.json ├── rollup.config.js ├── src ├── __tests__ │ └── react-hooks.ts └── react-hooks.ts ├── stories ├── addons.js ├── config.js ├── react-hooks.stories.js └── webpack.config.js ├── tsconfig.json └── yarn.lock /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 |