Jim Lynch Codes
  • Blog
  • About Jim

Writings about one coder's stories & experiences.

Understanding Ngrx Selectors

2/17/2017

0 Comments

 
As you may have guessed from the title, this post is all about understanding what selectors are in an Ngrx Angular 2 application and why one should want to use them. I'll admit it; for a while I didn't use selectors at all. The truth is that you don't *need* them to get a basic project up and running with Ngrx (and that's why I don't talk about them in my Getting Set Up With With Ngrx blog post), but as your application grows along with your understanding of Ngrx you may eventually want to refactor your code and the way you select data from the state to improve your project's consistency and prevent unnecessary duplication. So without further ado, let's talk about selectors! 

Store.Select()

Let's suppose that we are in a "smart" component, and we want to read some property off of our state so that it can be passed along to the dumb component and displayed on the screen. How would we do that? This is the Angular world, and one thing that's been a consistent value from AngularJS 1.1 all the way up to Angular 2  (and probably far on into the future of Angular) is the use of dependency injection. We inject the Store into our component via the constructor:
constructor(private store: Store<GlobalState>) {
  console.log('store: ' + this.store);
}
Because ngrx is based on observables and reactive programming, we can use this store object to basically "hook up" a variable in our component to the data in our store, and whenever the store's state changes the component is aware of this change and can update its own property or properties. Also notice that the store object is typed to a Store type (from the Ngrx library), and thid takes a GlobalState type (which I'll talk about in a bit). In order to do this "hooking up" functionality we use the select method from the Ngrx library:
this.store.select()

An Example State

It would be nice to have some context as to what we are actually selecting so I've contrived a simple example to illustrate how all the redux pieces come together when we select data from the store. First, let's define the state we will use. TypeScript is nice because it supports the concept of an interface, and here I've created an interface called MyState for a simple state object with two properties: userData, an object and contains a single number property named totalScore, and currentVideos, which is an array of objects of some undeclared data type.
export interface State {
  userData:
  {
    totalScore: number
  },
  currentVideos: Array<any>
};
I've also created a constant called initialState which conforms to the state interface and declares initial values for the various properties of the state object.  
export const initialState: State = {
  userData:
  {
    totalScore: 0
  },
  currentVideos: []
};
We'll then create a reducer to handle any Ngrx actions that are dispatched. Notice our ActionReducer uses the generics feature of TypeScript and takes another type; the type defined by our state interface.
export const mainStoreReducer: ActionReducer<State> =
  (state = initialState, action: Action) => {
We then add this line to our NgModule to let the core Ngrx library know that we would like to use this reducer.
 StoreModule.provideStore({mainState: mainStoreReducer,
                           otherState: otherReducer}),
When we use multiple reducers and stores Ngrx will behind the scenes combine them into one global state. We'll need this global state later when we are injecting our store object, but for now just know that the global stat interface is basically an object whose properties' types are the interfaces for the various state interfaces we are using in our app. 
export interface GlobalState {
  mainState: State,
  otherState: OtherState
}

Meanwhile, Back In The Component...

Ok! Now we've got all the plumbing in place for using Ngrx, and we're ready to select some data from our store. We'll first need to grab a reference to the Ngrx State service through dependency injection:
constructor(private store: Store<GlobalState>) {}

ngOnInit {
  // Do initialization stuff here...
}
Then we'll normally set up our selector either in our constructor in some lifecycle hook like ngOnInit. You could also execute your select statement later, but since the select method just hooks up your data to the store and from then on watches for updates, it almost always makes sense to start selecting from the store when the component starts up.

Pure String Selector

)Here's an example of what I call the "pure string selector". Notice that we are calling the select method on our store object, and as an argument into it we are passing a string that is the name of our reducer (or whatever top-level name we gave our store in the NgModule provideStore() method):
this.store.select("mainStoreReducer")
.subscribe((data: any) => {
  this.zone.run(() => {
    this.totalScore = data.useData.totalScore;
  });
});
While this works, we don't get any help from our IDE to tell us that we are indeed trying to access properties that actually exist. In addition, I then need to "unpack" the data object inside of the subscribe method.

Interface Hardcoding

Any experienced programmer will probably be aware that hardcoding strings can bring big-time problems from careless mistakes. With this method that I call "interface hardcoding" we can get rid of the hardcoded string by replacing it with an arrow function that "drills down" into our state to return the slice we desire.
this.store.select(s => s.mainStoreReducer.userData)
.subscribe((data: any) => {
  this.zone.run(() => {
    this.totalScore = data.totalScore;
  })
});
This is a little better that using pure strings because the IDE will immediately tell us if we spell something wrong or are trying to access a property that does not exist for that state's interface. The only downside to this is that if we want to select this data in multiple places (such as multiple components) then I am hardcoding this arrow function and and duplicating this drilling logic. If we decide later that we want to change our state object interface then we need to manually go into every file that is hardcoded for the old interface and update them. Ain't nobody got time for that!

Encapsulated Selector

The encapsulated selector gives us the benefits of IDE type support like the interface hardcoding, but here we do an extra step where we extract the hardcoded piece out. For example, here's an encapsulated constant called getCurrentVideosArray that contains the logic for pulling the videos out of our store:
export const getCurrentVideosArray= (state:GlobalState) => state.mainStoreReducer.currentVideos;
I can then simply use this constant inside of my select method like so:
import {getCurrentVideosArray} from "../../state-management/selectors/main-selector";

this.store.select(getCurrentVideosArray)
.subscribe((data: any) => {
  this.zone.run(() => {
    this.totalScore = data.totalScore;
  })
});
Now if you ever need to change your underlying interface you can just change it in one place- the getCurrentVideosArray const.

What Do You Think?

That's all for this post! So, what do you think? Have I convinced you of the power and beauty of encapsulated selectors? Let me know in the comments below! ;)
0 Comments

Your comment will be posted after it is approved.


Leave a Reply.

    ​Author

    Picture
    The posts on this site are written and maintained by Jim Lynch. About Jim...
    Follow @JimLynchCodes
    Follow @JimLynchCodes

    Categories

    All
    Actionscript 3
    Angular
    AngularJS
    Automated Testing
    AWS Lambda
    Behavior Driven Development
    Blockchain
    Blogging
    Business Building
    C#
    C / C++
    ClojureScript / Clojure
    Coding
    Community Service
    CS Philosophy
    Css / Scss
    Dev Ops
    Firebase
    Fitness
    Flash
    Front End
    Functional Programming
    Git
    Go Lang
    Haskell
    Illustrations
    Investing
    Java
    Javascript
    Lean
    Life
    Linux
    Logic Pro
    Music
    Node.js
    Planning
    Productivity
    Professionalism
    Python
    React
    Redux / Ngrx
    Refactoring
    Reusable Components
    Rust
    Security
    Serverless
    Shell Scripting
    Swift
    Test Driven Development
    Things
    TypeScript
    Useful Sites
    Useful Tools
    Video
    Website Development
    WebStorm
    Writing

    Archives

    August 2021
    February 2021
    January 2021
    October 2020
    September 2020
    May 2020
    April 2020
    February 2020
    January 2020
    December 2019
    October 2019
    September 2019
    August 2019
    July 2019
    June 2019
    May 2019
    April 2019
    March 2019
    February 2019
    January 2019
    December 2018
    November 2018
    October 2018
    September 2018
    August 2018
    June 2018
    May 2018
    April 2018
    March 2018
    February 2018
    January 2018
    December 2017
    November 2017
    October 2017
    September 2017
    August 2017
    July 2017
    May 2017
    April 2017
    March 2017
    February 2017
    January 2017
    December 2016
    November 2016
    October 2016
    September 2016
    August 2016
    July 2016
    June 2016
    May 2016
    April 2016
    March 2016
    February 2016
    January 2016
    December 2015
    November 2015
    October 2015

    RSS Feed

  • Blog
  • About Jim
JimLynchCodes © 2021