Created
April 22, 2020 01:43
-
-
Save fukaoi/6badc05ede7fc1e54d8195a266dba4f9 to your computer and use it in GitHub Desktop.
example code ref: https://www.bitovi.com/blog/rxjs-with-react-pt-1
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 React, {useState, useEffect} from 'react'; | |
import {of, observable, interval} from 'rxjs'; | |
import {map} from 'rxjs/operators'; | |
import {ajax} from 'rxjs/ajax'; | |
import './App.css'; | |
const api = `https://randomuser.me/api/?results=5&seed=rx-react&nat=us&inc=name&noinfo`; | |
const getName = user => `${user.name.first} ${user.name.last}`; | |
const names$ = ajax.getJSON(api).pipe(map(({results: users}) => users.map(getName))); | |
// const source = ['Adam', 'Brian', 'Chris']; | |
// const names$ = of(source); | |
// const names$ = interval(1000).pipe(map(i => source.slice(0, i+1))); | |
const useObservable = observable => { | |
const [state, setState] = useState(); | |
useEffect(() => { | |
const sub = observable.subscribe(setState); | |
return () => sub.unsubscribe(); | |
}, [observable]); | |
return state; | |
}; | |
function App() { | |
const names = useObservable(names$); | |
return ( | |
<div className="App"> | |
<h1>RxJS with React</h1> | |
<List items={names} /> | |
</div> | |
); | |
} | |
const List = ({items = [], loading = false}) => ( | |
<ul className={loading ? 'loading' : undefined}> | |
{items.map(item => ( | |
<li key={item}>{item}</li> | |
))} | |
</ul> | |
); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment