1.0.4 • Published 7 years ago
react-track-observable v1.0.4
react-track-observable
Tiny utility to render ECMAScript observable in React:
import { track } from 'react-track-observable';
// assume we have observable
{track.call(observable, value => (
<strong>{value}</strong>
))}
// ... or using proposed bind operator
{observable::track(value => (
<strong>{value}</strong>
))}Being called with this binded to observable you want to track,
track returns React component that literally track observable:
- subscribes on component creation
- unsubcribe on component disposal
- re-renders component when new value comes from the observable
Full example
import * as React from 'react';
import { render } from 'react-dom';
// This example uses Observable implementation from RxJs.
// However, library does not provide any observable implementation itself.
import { Observable } from 'rxjs/Rx';
import { track } from 'react-track-observable';
// here is the observable we would render
const observable = new Observable(observer => {
observer.next('hello');
setTimeout(() => observer.next('world'), 1000);
})
const App = () => (
<div>
<span>Rendering: </span>
{track.call(observable, value => (
<strong>{value}</strong>
))}
</div>
);
render(<App />, document.querySelector('body'));Installation
npm i --save react-track-observableAPI
track(renderFn)
track is expected to be called with this binded to ECMAScript Observable you want to track.
There are few implementations, and track will work with any of them as long as they follow the specification.
As with any function in js, you can use call method
of track function to invoke it with this binding of your choice.
Arguments
renderFn: (nextValue) => React.Elementfunction responsible for rendering values coming from observable.
Bind operator
Using proposed JavaScript bind operator you can directly call track on your observable.
There is Babel transform for bind operator.