Last active
January 6, 2021 05:19
-
-
Save ezekielchentnik/c924079e4b4896158b54ee470b1c2e2b to your computer and use it in GitHub Desktop.
react rxjs hook useStream
This file contains 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 React, { useState, useEffect, createContext, useContext } from "react"; | |
import { render } from "react-dom"; | |
import { BehaviorSubject, isObservable } from "rxjs"; | |
const Context = createContext(); | |
const Provider = Context.Provider; | |
const useStream = initialState => { | |
let source = isObservable(initialState) | |
? initialState | |
: new BehaviorSubject(initialState); | |
let currentState; | |
source.subscribe(val => (currentState = val)).unsubscribe(); | |
let [value, setValue] = useState(currentState); | |
let [subject] = useState(source); | |
useEffect(() => { | |
let sub = subject.subscribe(setValue); | |
return () => sub.unsubscribe(); | |
}, []); | |
return [value, subject.next.bind(subject)]; | |
}; | |
const Stream = () => { | |
const source = useContext(Context); | |
const [value, next] = useStream(source); | |
return ( | |
<div> | |
<div>{value}</div> | |
<button onClick={() => next(value + 1)}>+</button> | |
<button onClick={() => next(value - 1)}>-</button> | |
</div> | |
); | |
}; | |
const App = () => ( | |
<Provider value={new BehaviorSubject(0)}> | |
<Stream /> | |
<Provider value={new BehaviorSubject(5)}> | |
<Stream /> | |
</Provider> | |
</Provider> | |
); | |
const root = document.getElementById("root"); | |
render(<App />, root); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment