Kako izgraditi funkcionalnost pretraživanja GitHub u Reactu s RxJS 6 i Recompose

Ovaj je post namijenjen onima koji imaju React i RxJS iskustvo. Samo dijelim obrasce koje sam smatrao korisnim tijekom izrade ovog korisničkog sučelja.

Evo što gradimo:

Nema nastave, kukica životnog ciklusa ili setState.

Postaviti

Sve je na mom GitHubu.

git clone //github.com/yazeedb/recompose-github-ui cd recompose-github-ui yarn install 

masterGrana ima gotov projekt, pa naplata startgranu ako želite slijediti zajedno.

git checkout start

I voditi projekt.

npm start

Aplikacija bi trebala biti pokrenuta localhost:3000i evo našeg početnog korisničkog sučelja.

Otvorite projekt u svom omiljenom uređivaču teksta i pregledajte ga src/index.js.

Prekomponiraj

Ako ga još niste vidjeli, Recompose je prekrasan React pomoćni pojas za izradu komponenata u funkcionalnom stilu programiranja. Ima mnoštvo funkcija i teško bih odabrao svoje favorite.

To je Lodash / Ramda, ali za React. Također volim što podržavaju vidljive. Citiranje iz dokumenata:

Ispada da se velik dio API-ja React Component može izraziti u terminima uočljivosti

Vježbat ćemo taj koncept već danas! ?

Streaming naše komponente

Trenutno Appje obična komponenta React. Možemo ga vratiti putem vidljivog pomoću funkcije Recompose's komponentaFromStream.

Ova funkcija u početku generira nulu komponentu i ponovno se generira kad naš opažljivi vrati novu vrijednost.

Crtica konfiguracije

Prekomponirani tokovi slijede ECMAScript uočljivi prijedlog. Utvrđeno je kako bi promatrani trebali funkcionirati kada se na kraju isporuče modernim preglednicima.

Međutim, dok se u potpunosti ne implementiraju, oslanjamo se na knjižnice poput RxJS, xstream, most, Flyd itd.

Recompose ne zna koju biblioteku koristimo, tako da nudi setObservableConfigpretvorbu ES Observables u / iz onoga što nam treba.

Stvorite novu datoteku u srcpozvanom observableConfig.js.

I dodajte ovaj kôd kako biste Recompose učinili kompatibilnim s RxJS 6:

import { from } from 'rxjs'; import { setObservableConfig } from 'recompose'; setObservableConfig({ fromESObservable: from }); 

Uvezite ga u index.js:

import './observableConfig'; 

I mi smo spremni!

Prekomponiraj + RxJS

Uvoz componentFromStream.

import React from 'react'; import ReactDOM from 'react-dom'; import { componentFromStream } from 'recompose'; import './styles.css'; import './observableConfig'; 

I započnite redefiniranje Apps ovim kodom:

const App = componentFromStream((prop$) => { // ... }); 

Obavijest koja componentFromStreamuzima funkciju povratnog poziva očekujući prop$tok. Ideja je da naši propspostanu vidljivi, a mi ih mapiramo u komponentu React.

A ako ste koristili RxJS, znate savršenog operatora za mapiranje vrijednosti.

Karta

Kao što i samo ime govori, pretvarate se Observable(something)u Observable(somethingElse). U našem slučaju, Observable(props)u Observable(component).

Uvezite mapoperatora:

import { map } from 'rxjs/operators'; 

I redefinirajte aplikaciju:

const App = componentFromStream((prop$) => { return prop$.pipe( map(() => ( )) ); }); 

Još od RxJS 5 koristimo pipeumjesto lančanog povezivanja operatora.

Spremite i provjerite svoje korisničko sučelje, isti rezultat!

Dodavanje voditelja događaja

Sad ćemo našu inputreaktivnost učiniti malo reaktivnijom.

Uvezite createEventHandleriz Recompose.

import { componentFromStream, createEventHandler } from 'recompose'; 

I upotrijebite ga tako:

const App = componentFromStream((prop$) => { const { handler, stream } = createEventHandler(); return prop$.pipe( map(() => ( {' '} )) ); }); 

createEventHandlerje objekt s dva zanimljiva svojstva: handleri stream.

Ispod poklopca handlernalazi se odašiljač događaja koji gura vrijednosti na stream, a to je vidljivo emitiranje tih vrijednosti svojim pretplatnicima.

Tako ćemo kombinirati streamopažljivo i prop$opažljivo kako bismo pristupili inputtrenutnoj vrijednosti.

combineLatest je ovdje dobar izbor.

Problem s piletinom i jajima

To use combineLatest, though, both stream and prop$ must emit. stream won’t emit until prop$ emits, and vice versa.

We can fix that by giving stream an initial value.

Import RxJS’s startWith operator:

import { map, startWith } from 'rxjs/operators'; 

And create a new variable to capture the modified stream.

const { handler, stream } = createEventHandler(); const value$ = stream.pipe( map((e) => e.target.value), startWith('') ); 

We know that stream will emit events from input's onChange, so let’s immediately map each event to its text value.

On top of that, we’ll initialize value$ as an empty string — an appropriate default for an empty input.

Combining It All

We’re ready to combine these two streams and import combineLatest as a creation method, not as an operator.

import { combineLatest } from 'rxjs'; 

You can also import the tap operator to inspect values as they come:

import { map, startWith, tap } from 'rxjs/operators'; 

And use it like so:

const App = componentFromStream((prop$) => { const { handler, stream } = createEventHandler(); const value$ = stream.pipe( map((e) => e.target.value), startWith('') ); return combineLatest(prop$, value$).pipe( tap(console.warn), map(() => ( )) ); }); 

Now as you type, [props, value] is logged.

User Component

This component will be responsible for fetching/displaying the username we give it. It’ll receive the value from App and map it to an AJAX call.

JSX/CSS

It’s all based off this awesome GitHub Cards project. Most of the stuff, especially the styles, is copy/pasted or reworked to fit with React and props.

Create a folder src/User, and put this code into User.css:

And this code into src/User/Component.js:

The component just fills out a template with GitHub API’s standard JSON response.

The Container

Now that the “dumb” component’s out of the way, let’s do the “smart” component:

Here’s src/User/index.js:

import React from 'react'; import { componentFromStream } from 'recompose'; import { debounceTime, filter, map, pluck } from 'rxjs/operators'; import Component from './Component'; import './User.css'; const User = componentFromStream((prop$) => { const getUser$ = prop$.pipe( debounceTime(1000), pluck('user'), filter((user) => user && user.length), map((user) =>

{user}

) ); return getUser$; }); export default User;

We define User as a componentFromStream, which returns a prop$ stream that maps to an

.

debounceTime

Since User will receive its props through the keyboard, we don’t want to listen to every single emission.

When the user begins typing, debounceTime(1000) skips all emissions for 1 second. This pattern’s commonly employed in type-aheads.

pluck

This component expects prop.user at some point. pluck grabs user, so we don’t need to destructure our props every time.

filter

Ensures that user exists and isn’t an empty string.

map

For now, just put user inside an

tag.

Hooking It Up

Back in src/index.js, import the User component:

import User from './User';

And provide value as the user prop:

return combineLatest(prop$, value$).pipe( tap(console.warn), map(([props, value]) => ( {' '} )) ); 

Now your value’s rendered to the screen after 1 second.

Good start, but we need to actually fetch the user.

Fetching the User

GitHub’s User API is available here. We can easily extract that into a helper function inside User/index.js:

const formatUrl = (user) => `//api.github.com/users/${user}`; 

Now we can add map(formatUrl) after filter:

You’ll notice the API endpoint is rendered to the screen after 1 second now:

But we need to make an API request! Here comes switchMap and ajax.

switchMap

Also used in type-aheads, switchMap’s great for literally switching from one observable to another.

Let’s say the user enters a username, and we fetch it inside switchMap.

What happens if the user enters something new before the result comes back? Do we care about the previous API response?

Nope.

switchMap will cancel that previous fetch and focus on the current one.

ajax

RxJS provides its own implementation of ajax that works great with switchMap!

Using Them

Let’s import both. My code is looking like this:

import { ajax } from 'rxjs/ajax'; import { debounceTime, filter, map, pluck, switchMap } from 'rxjs/operators'; 

And use them like so:

const User = componentFromStream((prop$) => { const getUser$ = prop$.pipe( debounceTime(1000), pluck('user'), filter((user) => user && user.length), map(formatUrl), switchMap((url) => ajax(url).pipe( pluck('response'), map(Component) ) ) ); return getUser$; }); 

Switch from our input stream to an ajax request stream. Once the request completes, grab its response and map to our User component.

We’ve got a result!

Error handling

Try entering a username that doesn’t exist.

Even if you change it, our app’s broken. You must refresh to fetch more users.

That’s a bad user experience, right?

catchError

With the catchError operator, we can render a reasonable response to the screen instead of silently breaking.

Import it:

import { catchError, debounceTime, filter, map, pluck, switchMap } from 'rxjs/operators'; 

And stick it to the end of your ajax chain.

switchMap((url) => ajax(url).pipe( pluck('response'), map(Component), catchError(({ response }) => alert(response.message)) ) ); 

At least we get some feedback, but we can do better.

An Error Component

Create a new component, src/Error/index.js.

import React from 'react'; const Error = ({ response, status }) => ( 

Oops!

{status}: {response.message}

Please try searching again.

); export default Error;

This will nicely display response and status from our AJAX call.

Let’s import it in User/index.js:

import Error from '../Error'; 

And of from RxJS:

import { of } from 'rxjs'; 

Remember, our componentFromStream callback must return an observable. We can achieve that with of.

Here’s the new code:

ajax(url).pipe( pluck('response'), map(Component), catchError((error) => of()) ); 

Simply spread the error object as props on our component.

Now if we check our UI:

Much better!

A Loading Indicator

Normally, we’d now require some form of state management. How else does one build a loading indicator?

But before reaching for setState, let’s see if RxJS can help us out.

The Recompose docs got me thinking in this direction:

Instead of setState(), combine multiple streams together.

Edit: I initially used BehaviorSubjects, but Matti Lankinen responded with a brilliant way to simplify this code. Thank you Matti!

Import the merge operator.

import { merge, of } from 'rxjs'; 

When the request is made, we’ll merge our ajax with a Loading Component stream.

Inside componentFromStream:

const User = componentFromStream((prop$) => { const loading$ = of(

Loading...

); // ... });

A simple h3 loading indicator turned into an observable! And use it like so:

const loading$ = of(

Loading...

); const getUser$ = prop$.pipe( debounceTime(1000), pluck('user'), filter((user) => user && user.length), map(formatUrl), switchMap((url) => merge( loading$, ajax(url).pipe( pluck('response'), map(Component), catchError((error) => of()) ) ) ) );

I love how concise this is. Upon entering switchMap, merge the loading$ and ajax observables.

Since loading$ is a static value, it’ll emit first. Once the asynchronous ajax finishes, however, it’ll emit and be displayed on the screen.

Before testing it out, we can import the delay operator so the transition doesn’t happen too fast.

import { catchError, debounceTime, delay, filter, map, pluck, switchMap, tap } from 'rxjs/operators'; 

And use it just before map(Component):

ajax(url).pipe( pluck('response'), delay(1500), map(Component), catchError((error) => of()) ); 

Our result?

I’m wondering how far to take this pattern and in what direction. Please share your thoughts!