Reactive Extensions are everywhere – I wanted to try the JavaScript version of the library, so below is a sample React component demonstrating a “fake” service call that might occur within the fetch function. The setTimeout is used simply to simulate some latency in the call.
To add rxjs simple use
yarn add rxjs
Now here’s the sample component code…
import {Observable, Subscriber, Subscription} from 'rxjs'; interface ServiceState { data: string; } class ServiceComponent extends Component<{}, ServiceState> { _subscription!: Subscription; constructor(prop: any) { super(prop); this.state = { data : "Busy" }; } fetch() : Observable<string> { return Observable.create((o: Observer<string>) => { setTimeout(() => { o.next('Some data'); o.complete(); }, 3000); }); } componentDidMount() { this._subscription = this.fetch().subscribe(s => { this.setState({data: s}) }); } componentWillUnmount() { if(this._subscription) { this._subscription.unsubscribe(); } } render() { return ( <div>{this.state.data}</div> ); } }
In this example we have the fetch function returns an instance of an Observable of type string. We then subscribe to this within the componentDidMount function, which is called when the component is inserted into the DOM and then we subscribe to the Observable, updates will be applied to the component’s state.
The componentWillUnmount is called when the component is removed from the DOM and hence we unsubscribe from the Observable.