Using Connect with Local Component State
We have really already learned most of what we need to know about the
connect function and how it integrates with our state management approach.
This lesson will mostly be a continuation of the last, but this time we will be
refactoring the services in the Giflist application that we created.
Once again, if you don’t have that on your computer and want to follow along, you can find it here.
The interesting thing about the Giflist application is that we are also using
our state management approach for managing state directly within
a component. We will refactor that component to use connect as well as our
shared RedditService.
We will not be dealing with any new concepts in this lesson, just practicing them in a different context. So, again, I will encourage you to attempt these refactors yourself and I will post my solution below.
Refactor the GifPlayerComponent
Click here to reveal solution
Solution
Here are the refactored reducers:
//reducers const nextState$ = merge( this.videoLoadStart$.pipe(map(() => ({ status: 'loading' as const }))), this.videoLoadComplete$.pipe(map(() => ({ status: 'loaded' as const }))) );
connect(this.state) .with(nextState$) .with(this.togglePlay$, (state) => ({ playing: !state.playing }));Perhaps I am just weird, but isn’t refactoring to connect just so satisfying?
Refactor the RedditService
Click here to reveal solution
Solution
Again, here are the refactored reducers:
constructor() { //reducers const nextState$ = merge( this.subredditChanged$.pipe( map(() => ({ loading: true, gifs: [], lastKnownGif: null, })) ), this.error$.pipe(map((error) => ({ error }))) );
connect(this.state) .with(nextState$) .with(this.gifsLoaded$, (state, response) => ({ gifs: [...state.gifs, ...response.gifs], loading: false, lastKnownGif: response.lastKnownGif, })); }As you can see, the general process here is pretty much the same with everything
we do — the connect function mostly just gets rid of a bunch of boilerplate
for us.
We have already seen one situation where some further accommodations were
required — like refactoring to use an error$ source instead of handling that
in the subscribe — in the next lesson we will discuss another advanced
consideration that we will run into in our last application.