Last active
November 3, 2019 12:58
-
-
Save ryuheechul/f6ed848dd320e9dd14ed26975d0ff2e8 to your computer and use it in GitHub Desktop.
useStream React Hook
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
| import { useEffect, useState } from "react"; | |
| export function useStream($) { | |
| const [value, setValue] = useState([]); | |
| useEffect(() => { | |
| const subs = $.subscribe({ | |
| next: v => setValue(v), | |
| complete: () => console.log("stream completed in useStream"), | |
| error: e => { console.error(e)} | |
| }); | |
| return () => subs.unsubscribe(); | |
| }, [$]); | |
| return value; | |
| } |
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
| // my-comp.js | |
| import React from "react"; | |
| import { useStream } from "./use-stream.js"; | |
| export function MyComp({ $ /* an RxJS Stream (or Observable) */, title }) { | |
| const value = useStream($); | |
| return ( | |
| <div> | |
| <p>{title}</p> | |
| <pre>{value}</pre> | |
| </div> | |
| ); | |
| } |
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
| // example.js | |
| import React from "react"; | |
| import ReactDOM from "react-dom"; | |
| import { fromEvent } from 'rxjs'; | |
| import { scan } from 'rxjs/operators'; | |
| import { MyComp } from "./my-comp.js"; | |
| const myStream = fromEvent(document, 'click').pipe(scan(count => count + 1, 0)) | |
| function App() { | |
| return ( | |
| <div> | |
| <p>This is an example app using useStream hook</p> | |
| <MyComp title="mouse click monitor" $={myStream} /> | |
| </div> | |
| ); | |
| } | |
| function mount() { | |
| const rootElement = document.getElementById("root"); | |
| ReactDOM.render(<App />, rootElement); | |
| } | |
| mount(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment