<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by w3ird0h on Medium]]></title>
        <description><![CDATA[Stories by w3ird0h on Medium]]></description>
        <link>https://medium.com/@w3ird0h?source=rss-a2ca7d5c0904------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8K-Jd1ziBnnmMJI2uY3N3w.jpeg</url>
            <title>Stories by w3ird0h on Medium</title>
            <link>https://medium.com/@w3ird0h?source=rss-a2ca7d5c0904------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:14:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@w3ird0h/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[htmx: Big Wins for State Management]]></title>
            <link>https://medium.com/@w3ird0h/htmx-big-wins-for-state-management-3f8f5bf327f7?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f8f5bf327f7</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 06:14:42 GMT</pubDate>
            <atom:updated>2023-11-03T15:58:11.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c0nOYqgTiT0PD9SW" /><figcaption>Photo by <a href="https://unsplash.com/@etiennegirardet?utm_source=medium&amp;utm_medium=referral">Etienne Girardet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://htmx.org/">htmx - high power tools for html</a></p><blockquote>htmx gives you access to <a href="https://htmx.org/docs/#ajax">AJAX</a>, <a href="https://htmx.org/docs/#css_transitions">CSS Transitions</a>, <a href="https://htmx.org/docs/#websockets">WebSockets</a> and <a href="https://htmx.org/docs/#sse">Server Sent Events</a> directly in HTML, using <a href="https://htmx.org/reference/#attributes">attributes</a>, so you can build <a href="https://htmx.org/examples/">modern user interfaces</a> with the <a href="https://en.wikipedia.org/wiki/HATEOAS">simplicity</a> and <a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">power</a> of hypertext</blockquote><blockquote>htmx is small (<a href="https://unpkg.com/htmx.org/dist/">~14k min.gz’d</a>), <a href="https://github.com/bigskysoftware/htmx/blob/master/package.json">dependency-free</a>, <a href="https://htmx.org/extensions/">extendable</a>, IE11 compatible &amp; has <strong>reduced</strong> code base sizes by <a href="https://htmx.org/essays/a-real-world-react-to-htmx-port/">67% when compared with react</a></blockquote><blockquote>TL;DR: The biggest win with this tech is the simplification of state management for applications that make it to the browser. You should give this project a chance.</blockquote><p><em>Update 20231103: Hey! I started building and exploring with htmx and I’m streaming that on Twitch: </em><a href="https://www.twitch.tv/w3ird0h">https://www.twitch.tv/w3ird0h</a></p><p><em>…and, I’m uploading all of that to a YouTube playlist here: </em><a href="https://youtube.com/playlist?list=PLt1G2LE0boHNhr7pbLYvFKnze5G2LX_3O&amp;si=lSAoHo4kzLwwvl-_"><em>https://youtube.com/playlist?list=PLt1G2LE0boHNhr7pbLYvFKnze5G2LX_3O&amp;si=lSAoHo4kzLwwvl-_</em></a></p><p>My take isn’t novel, it’s similar to what other people have recognized in the industry… and so far as I’ve been paying attention I haven’t heard anything new yet…</p><p>On the “not hearing anything new yet”, it’s important to me because as I dig into the tech, knowing the boundaries that should be prodded with it and thinking through what could be tested hopefully means that I’m not yet missing obvious in my research.</p><p>This tech and techniques are not groundbreaking, though this one is currently gaining momentum. It’s certainly part of the “oh so we’re going back to the server now, huh?” take that you’ll hear at the watercooler (do those exist anymore? I haven’t been into an office in ~4 years).</p><blockquote>The biggest win with this tech is the simplification of state management for applications that make it to the browser.</blockquote><p>We can dramatically reduce cognitive load and lines of code for web application state management by <strong>executing the logic for what to present to the client once, </strong>because we no longer duplicate logic or manage (as much) state on the client to know what to display. To boot, we also are met with a delightful DX for the client to hydrate.</p><p>That’s dev time saved, product time saved, time saved because less meetings, because less learning needed (after the initial hurdle we have to jump over to understand how to wield htmx properly). We could even still use something like React to produce the html fragments on the server, but we reduce the complexity of state synchronization between layers. I’ve basically made a living and put food on the table for my family for years now because I’m really good at that kind of stuff (state management)… and this has good potential to be a superb enabler for making web dev much more productive.</p><blockquote>Imagine not having to learn React/Angular/Vue etc. Not having to learn redux, hooks, vuex, ngrx, etc… just to show the right thing on the page.</blockquote><p>Here’s an example:</p><p>Imagine needing to present a delete button to a user.</p><p>In SPA land, it goes <em>something</em> like this:</p><ul><li>Assuming we’re on the route already where a component is loaded</li><li>Maybe when the component loads an API request is made to load a list</li><li>Server receives request, builds some JSON to send the list set over to the client, and it includes something like a canDelete prop on some of the items... <strong>so we do work to understand if the client should see a delete button</strong></li><li>Client receives response, handles that somehow, maybe the data is stored higher up in a state tree, maybe it’s local</li><li>Client processes the data for the component, building HTML and utilizes the canDelete prop to understand whether or not to build the delete button.. <strong>so we do work to understand if the client should see a delete button</strong></li></ul><p>In htmx land, it goes something like this:</p><ul><li>HTML element setup to trigger to get data</li><li>Server builds html, sends that to client</li><li>htmx places html where we told it to</li></ul><p>Here’s what we <strong>don’t</strong> do in htmx land:</p><ul><li>Care about choosing or learning a SPA</li><li>Care about choosing or learning about a flavor of state management techniques that work well with our SPA choice</li><li>Store the data (possibly) for later usage on the client</li><li>Duplicate the canDelete? logic on the client, because we built the HTML already on the server and sent it over the wire</li></ul><p>I skipped on this tech when I first caught wind of it and figured it was some kiddie project that wouldn’t hold to the challenge of engaging and interactive web applications that feel fluid.. but after I saw some really stellar examples, I’ve become intrigued.</p><p>Right now there’s a rumbling beginning that this stuff and likely competitors are coming for the front-end landscape, I think that’s going to ripple out and we’re going to see mass adoption of stuff like this. We’re in a phase of pre-mass adoption, and tooling around it is going to skyrocket. We’re going to be knee deep in shitty blog posts and tutorials. It’s a living.</p><p>I think Tailwind will see increased usage alongside htmx.</p><p>A friend shared “most orgs [will have the] desire to build with really complicated stuff like React / Angular”, and I agree. At work, adoption for this tech will take significant effort and will need concrete examples for viability.</p><p>Doing a project that puts together dummy scenarios to showcase it’s effectiveness and pushing it to it’s limits could be helpful and probably one way I’d start to approach research.</p><p>I don’t think the intention of the growing community around the tech is to kill off JS usage entirely, but certainly to reduce it’s prevalence and lean into it when it makes sense.</p><p>You should give this project a chance. I know I will.</p><p><em>Update 20231103: Hey! I started building and exploring with htmx and I’m streaming that on Twitch: </em><a href="https://www.twitch.tv/w3ird0h">https://www.twitch.tv/w3ird0h</a></p><p><em>…and, I’m uploading all of that to a YouTube playlist here: </em><a href="https://youtube.com/playlist?list=PLt1G2LE0boHNhr7pbLYvFKnze5G2LX_3O&amp;si=lSAoHo4kzLwwvl-_"><em>https://youtube.com/playlist?list=PLt1G2LE0boHNhr7pbLYvFKnze5G2LX_3O&amp;si=lSAoHo4kzLwwvl-_</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f8f5bf327f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EventStore + NestJS #1: A New Series]]></title>
            <link>https://medium.com/@w3ird0h/eventstore-nestjs-1-a-new-series-259832f50a37?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/259832f50a37</guid>
            <category><![CDATA[eventstore]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Sun, 15 May 2022 01:43:58 GMT</pubDate>
            <atom:updated>2023-09-06T18:34:23.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gr257Sv33XQ_kHE6ranCUg.png" /><figcaption>Person on a raft surrounded by data. Source: EventStore.com</figcaption></figure><blockquote><strong>Update 20230906: I got distracted with some other work stuff when I spun up this post… I’ll still be working through my research here and posting the journey but it’s not written.</strong></blockquote><p>I’ve been enticed to fully realize the power of an event-sourced system, but so often either the business or the engineering crew is reluctant to dive in.</p><p>I did get one small opportunity to give it a shot on a project. I drank the kool-aid…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8JKjvY4etTY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8JKjvY4etTY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8JKjvY4etTY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d07793cc1c81cf9796fdcee483170ea/href">https://medium.com/media/9d07793cc1c81cf9796fdcee483170ea/href</a></iframe><p>… and then I utilized MongoDB in order to save immutable events and I folded over them using the concept of an aggregateRootId in order to correlate read models. I even utilized NestJS’s CQRS module to provide an abstracted event-driven architecture that gave me the feels of a reactive system. It worked, that project shipped to production, but it was child&#39;s play.</p><p>These days I’m highly invested in event-driven architecture (EDA). Event Sourcing (ES) itself doesn’t even feel like the goal anymore, but I can’t ignore how simplified it feels for the development of EDA that I really need to give something like <a href="https://www.eventstore.com/">EventStore</a> a fair trial.</p><p>Who knows how far I’ll get with this side quest, but here’s some of what I’m thinking:</p><ul><li>Start with a single insecure local Docker node</li><li>Learn all about EventStore</li><li>Use <a href="https://nestjs.com/">NestJS</a> to play with it</li><li>Document me pretending like I know what I’m doing</li></ul><h4>Articles in this series</h4><ul><li>EventStore + NestJS #1: A New Series (you are here)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=259832f50a37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue 3 Reactive State Management]]></title>
            <link>https://medium.com/@w3ird0h/vue-3-reactive-state-management-175b216a63fb?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/175b216a63fb</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Thu, 15 Apr 2021 16:05:57 GMT</pubDate>
            <atom:updated>2024-10-04T15:53:30.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXkGivvPdSiEpP-QuToPyQ.jpeg" /><figcaption><a href="https://unsplash.com/@parrish">https://unsplash.com/@parrish</a></figcaption></figure><blockquote>Update 8/4/22 — Definitely not working on this right now, but it’s already been iterated on and working in production for a couple of years. Will make a new post sometime with the updated stuff! I’m not working on open sourcing it at this time.</blockquote><h3>Introduction</h3><p>Sup nerds 👋</p><p>This is not an opinion piece, nor is it an introduction to front-end state management techniques or reactive programming.</p><p>There be no framework bashing here.</p><p>This is a write-up of an event-driven reactive approach to managing state in Vue 3 applications that leverages native Vue APIs.</p><h4>Why not React? Why not Angular? Why not X?</h4><p>Good question 🤔</p><p>On the new team that I help we chose to go with Vue. We determined it was going to be the easiest on the team to pick up, and we needed a library that was good at providing incremental value that also came with some guardrails.</p><blockquote>When choosing Vue, general <a href="https://svelte.dev/">Svelte </a>adoption and <a href="https://www.typescriptlang.org/">TypeScript </a>suppport wasn’t ready yet, and no one believes me when I tell them <a href="https://cycle.js.org/">Cycle </a>is really where it’s at.</blockquote><p>We work in the healthcare industry. IE11 still needs support in the space we occupy. There’s headway being made to jettison the support but we would never leave a healthcare provider in the dust. Vue 3 does not have support for IE11 yet. Even though it’s on the roadmap, it’s <a href="https://twitter.com/youyuxi/status/1347290990932013056">not likely to be implemented soon</a> and <a href="https://github.com/vuejs/vue/projects/6#card-16117770">we’ve already passed the first estimate for implementation</a>… and oops, edit, <a href="https://github.com/vuejs/rfcs/pull/294">now it looks like it never will</a>.</p><p>I chose to introduce the <a href="https://github.com/vuejs/composition-api">Vue 2 Composition API Plugin</a> to allow for an easier migration path from 2 👉3 and so we could retain IE11 support while using the modern reactive Vue APIs.</p><blockquote>Yes, this means Vue 2 is being used in this writeup, but it will all look and feel like Vue 3 and how the new Reactive and Composition APIs are being used is not likely to change drastically during the migration 🤞</blockquote><h4>Why not Vuex? Why not pure Composition API? Why not X?</h4><p>Good question 🤔</p><p>By choosing the migration path with the Composition API it left <a href="https://vuex.vuejs.org/">Vuex </a>support questionable as I didn’t want to mix it with the new APIs via the plugin. When we first started development with the technique Vuex wasn’t able to handle the Composition API (<a href="https://next.vuex.vuejs.org/">it’s closer now</a>).</p><p>Vuex also doesn’t meet my standards for a state management library. It’s close… but having some experience in the front-end state management space since rollin’ my own and then getting more sophisticated with using things like <a href="https://github.com/Yomguithereal/baobab">Baobab </a>in <a href="https://angularjs.org/">AngularJS</a>, moving on to stuff like <a href="https://redux.js.org/">Redux</a>, <a href="https://mobx-state-tree.js.org/intro/welcome">MST</a>, <a href="https://xstate.js.org/docs/">XState</a>, <a href="https://ngrx.io/">NgRx</a>.. and generally playing with them all in some capacity…</p><p>I learned I enjoy a reactive event-driven declarative approach over the imperative nature of options like <a href="https://datorama.github.io/akita/">Akita</a>, MST, plain Hooks in React, Vuex, etc.</p><blockquote>👆 No bad blood there, and some people may disagree with my characterizations, but this is the internet and you’ll never catch me!</blockquote><p>I first started using this technique in late 2019 by implementing it in React, using a combination of <a href="https://reactjs.org/docs/hooks-intro.html">Hooks</a>, <a href="https://immerjs.github.io/immer/">Immer</a>, and <a href="https://rxjs.dev/">RxJS</a>. The rest of the post is about what it looks like adapted to Vue 3.</p><h4>What’s different about your technique?</h4><p>Nothing here will be drastically different than anything else you’ll find out there. If you go searching for “state management in Vue 3”, you’re basically going to find the same stuff here as you will there.. though, the approach detailed here leans heavily into declarative, reactive architecture, and guardrails.</p><blockquote><a href="https://github.com/kiaking/rfcs/blob/vuex-5/active-rfcs/0000-vuex-5.md">Vuex 5 is inching towards things you’ll find here</a>, though important parts of the API remain firmly in the imperative camp, and that’s not my jam.</blockquote><h3>Architecture of Sink</h3><blockquote>To simplify references to the technique I’ll give it a name for the purpose of this post and call it <strong>Sink.</strong></blockquote><h4>Breakin’ It Down</h4><p><strong>Sink</strong> uses a collection of <strong>modules </strong>to organize all of the state management concerns, they are responsible for:</p><ul><li>Modeling and storing data</li><li>Reacting to events</li><li>Propagating data changes throughout the application</li></ul><p>Generally speaking, if you have a new concern or entity that needs tracking, create a new <strong>module</strong>.</p><h4><strong>Sink Has Three Components</strong></h4><ul><li>Stores</li><li>Projections</li><li>Sinks</li></ul><h4>Dataflow In Sink</h4><ul><li>Data lives in <strong>stores</strong></li><li>Read work is done through <strong>projections</strong></li><li>Events are broadcast to the system through one shared channel</li><li>Event handlers (<strong>sinks</strong>) listen to one or more events and respond to them</li><li>Non-read work is done inside of a <strong>sink</strong></li></ul><blockquote>event 👉 handle it 👉 update store 👉 projections based on stores 👉 consumers</blockquote><h3>Modules</h3><blockquote>A <strong>module </strong>consists of a <strong>store</strong>, <strong>projections</strong>, and <strong>sinks. </strong>All <strong>modules </strong>are included when we instantiate <strong>Sink, </strong>and they activate when we initialize <strong>Sink. Modules</strong> help to organize concerns but also play an important role under the hood to help make everything work.</blockquote><p>Create a <strong>module </strong>👇</p><pre>import { createModule } from &#39;sink&#39;;<br>import { fooStore as store } from &#39;./store&#39;;<br>import * as projections from &#39;./projections&#39;;<br>import * as sinks from &#39;./sinks&#39;;<br><br>export const fooModule = createModule({<br>  store,<br>  projections,<br>  sinks,<br>});</pre><ul><li>createModule takes an Object which accepts a store , projections , and sinks</li></ul><p>Include the <strong>module </strong>into our instance of <strong>Sink</strong>👇</p><pre>import { Sink } from &#39;sink&#39;;<br>import { fooModule } from &#39;@/foo&#39;;</pre><pre>export default new Sink({<br>  modules: [<br>    fooModule,<br>  ],<br>});</pre><p>Initialize <strong>Sink </strong>👇</p><pre>import sink from &#39;@/sink&#39;;</pre><pre>export default defineComponent({<br>  setup() {<br>    sink.initialize();<br>  }<br>});</pre><ul><li>This is done at the highest level needed — for simplicity, you’d do this in your App.vue</li><li>Once you initialize your instance of <strong>Sink</strong>, the <strong>modules </strong>are activated</li></ul><h3>Stores</h3><blockquote>The <strong>store </strong>is how your data is modeled and where your raw state lives.</blockquote><p>Start with an <a href="https://www.typescriptlang.org/docs/handbook/interfaces.html">interface</a> 👇</p><pre>export interface FooState {<br>  id: string;<br>  createdAt: string;<br>  firstName: string;<br>  lastName: string;<br>  bar: any[];<br>}</pre><p>Create the <strong>store </strong>👇</p><pre>import { createStore } from &#39;sink&#39;;<br>import { FooState } from &#39;./foo-state.interface&#39;;</pre><pre>export const fooStateKey = &#39;foo-state&#39;;</pre><pre>export const fooInitialState: FooState = {<br>  id: null;<br>  createdAt: null;<br>  firstName: null;<br>  lastName: null;<br>  bar: [];<br>}</pre><pre>export const fooStore = createStore(<br>  fooStateKey,<br>  fooInitialState,<br>);</pre><ul><li>We create a <strong>key</strong> that gets associated with the <strong>store</strong></li><li>Here we also create the initial state of the <strong>store</strong></li></ul><h3>Projections</h3><blockquote>A <strong>projection </strong>is a <strong>computed </strong>value that’s source is <strong>raw state</strong> and/or other <strong>projections. </strong>These are reactive. Changes to the source of a <strong>projection </strong>trigger updates to flow automatically to their consumers. Multiple consumers of the same <strong>projection </strong>do not trigger uneccessary computations.</blockquote><p>Start by modeling a <strong>projection </strong>with an interface (if applicable)<em> 👇</em></p><pre>export interface SomeProjection {<br>  id: number;<br>  createdAtFormatted: string;<br>  name: string;<br>}</pre><p>Create a <strong>projection map<em> </em></strong><em>👇</em></p><pre>import { SomeProjection } from &#39;./some-projection.interface&#39;;</pre><pre>export interface FooProjectionMap {<br>  &#39;foo.some-projection&#39;: SomeProjection;<br>}</pre><blockquote>A <strong>projection map</strong> enables some type checking saftey when creating <strong>projections</strong>, and also helps the shape of the projection come through when being consumed.</blockquote><p>Create a <strong>projector</strong><em> 👇</em></p><pre>import { createProjector } from &#39;state-sink&#39;;<br>import { FooState } from &#39;./foo-state.interface&#39;;</pre><pre>export const fooProjector = createProjector&lt;<br>  FooProjectionMap,<br>  FooState,<br>&gt;();</pre><blockquote>A <strong>projector </strong>is a utility that makes it easier to create projections.</blockquote><h3>Creating Projections</h3><p>Now with some of the setup out of the way, you just add <strong>projections </strong>here, and they automatically become available to use throughout the application.. in <strong>components</strong>, other <strong>projections</strong>, and <strong>sinks</strong>.</p><pre>import { SomeProjection } from &#39;./some-projection.interface&#39;;<br>import { fooProjector } from &#39;./foo-projector&#39;;</pre><pre>export const someProjection = fooProjector&lt;SomeProjection&gt;(<br>  &#39;foo.some-projection&#39;,<br>  ({ store }) =&gt; ({<br>    id: store.id;<br>    createdAtFormatted: store.createdAt.slice(0, 10),<br>    name: `${store.firstName} ${store.lastName}`<br>  })<br>)</pre><ul><li>The projector takes two arguments: a string and a function</li><li>&#39;foo.some-projection&#39; This string is passed as the <strong>key</strong> to the <strong>projection</strong>.. and because of how we created the <strong>projector</strong>, it’s strongly typed. It only lets you pass valid strings that were described by the <strong>projector map</strong>. You’ll see this <strong>key </strong>again later when we consume this <strong>projection</strong></li><li>({ store }) We’re destructuring the <strong>store</strong> out of the first parameter passed to the function to get access to values of the reactive <strong>raw state</strong>. This is the <strong>store</strong> for the Foo <strong>module</strong>, and TypeScript will understand its shape</li><li>The id, createdAt, firstName, and lastName are pieces of <strong>raw state</strong> from our <strong>store</strong>. The <strong>projection </strong>tracks changes to those and automatically updates consumers with a newly computed value</li></ul><h3>Consuming Projections 😋</h3><h4>Projections Inside of a Vue Component</h4><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    {{ someProjection.id }}<br>    {{ someProjection.createdAtFormatted }}<br>    {{ someProjection.name }}<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>import sink from &#39;@/sink&#39;;</pre><pre>defineComponent({<br>  setup () {<br>    return {<br>      someProjection: sink.select(&#39;foo.some-projection&#39;),<br>    }<br>  }<br>})<br>&lt;/script&gt;</pre><ul><li>We’ve imported our instance of sink , and not <strong>Sink </strong>itself</li><li>The select method is aware of all available <strong>projection keys</strong>,<strong> </strong>so as you start typing TypeScript should give you hints in your IDE for what is available. It’s up to the team to decide on a naming convention to help organize your <strong>projection keys</strong></li></ul><p>It’s not obvious here in the example code so I’m just going to point out…</p><blockquote>👉 If any of the data for that projection changes, all you have to do to get this component to render the new data is already done, the change propagates automatically and Vue will take care of the rendering.</blockquote><p>Not grounding breaking, just connecting the dots! 😺</p><h4>Projections Inside of Projections</h4><pre>import { barProjector } from &#39;./bar-projector&#39;;</pre><pre>export const anotherProjection = barProjector&lt;string&gt;(<br>  &#39;bar.another-projection&#39;,<br>  ({ select }) =&gt; {<br>    const someProjection = select(&#39;foo.some-projection&#39;).value;<br>    return someProjection.id.toString();<br>  }<br>)</pre><ul><li>All <strong>projections </strong>in the application are available to you here through <em>select</em></li></ul><h4>Projections Inside of a Sink</h4><pre>export const someSink = createSink({<br>  sources: [SomethingHappened],<br>  sink({ select }) {<br>    const someProjection = select(&#39;foo.some-projection&#39;).value;<br>  },<br>});</pre><ul><li>We haven’t looked at <strong>sinks</strong> yet, but that 👆 just goes to show that <strong>projections</strong> are also available in <strong>sinks</strong> through a similar API</li></ul><h3>Sinks</h3><blockquote><strong>Sinks </strong>are event handlers. All events are streamed through the same channel, and all <strong>sinks </strong>have access to that channel. You define which events the <strong>sink </strong>should care about by listing the events as <strong>sources. </strong>Add at least one <strong>event </strong>as a <strong>source</strong>, but you can add as many as you like. The idea for the naming conventions align loosely with <a href="https://en.wikipedia.org/wiki/Sink_(computing)">sinks</a> and<a href="https://cycle.js.org/#-dataflow"> Cycle’s</a> dataflow architecture.</blockquote><h4>Creating a Sink and Manipulating a Store</h4><blockquote>The only place you can manipulate a <strong>module’s store</strong> is through it’s associated <strong>sinks</strong>. This helps create some guardrails in the architecture… need to know how a <strong>store</strong> is changing? Look at that<strong> module’s sinks</strong>.</blockquote><pre>import { createSink } from &#39;sink&#39;;<br>import { SomethingHappened, SomethingElseHappened } from &#39;@/foo&#39;;</pre><pre>export const someFooSink = createSink({<br>  sources: [SomethingHappened, SomethingElseHappened],<br>  sink({ event, store }) {<br>    store.bar.push(event.payload.barItem);<br>  },<br>});</pre><ul><li>The <strong>sink</strong> created here is included into the FooModule shown previously, all you need to do after that setup is add <strong>sinks</strong> here and they’ll be automatically included</li><li>The event being destructured here could be SomethingHappened or SomethingElseHappened, both of which have a payload of something called a barItem … showcasing that you can have multiple <strong>events </strong>as the <strong>source </strong>for the <strong>sink</strong> to be triggered, and that you get direct access to the <strong>event</strong></li><li>The store being destructured here is for the FooModule , earlier we defined a property named bar that is an Array of anything.. and here we simply push those items into the Array to affect the <strong>state </strong>of the <strong>store</strong></li></ul><h4>Sinks with Network Requests, Managing Loading State, and Error Handling</h4><p>It’s common to declare that something is loading while doing a network request and to wrap that work up with error handling. Those sorts of tasks are supposed to be straight forward with <strong>Sink</strong>, they look something like this 👇</p><pre>export const getSomeStuff = createSink({<br>  sources: [SomePageLoaded],<br>  async sink({ store }) {<br>    store.loading = true;</pre><pre>    try {<br>      const { data } = await axios.get(&#39;/api/stuff&#39;);<br>      store.data = data;<br>    } catch (error) {<br>      store.errorMessage = error.message;<br>    } finally {<br>      store.loading = false;<br>    }<br>  },<br>});</pre><ul><li>Declare the sink as an <strong>async </strong>function, and <strong>await</strong> your data</li><li>Wrap the work in a try/catch , handle it appropriately</li><li>Use a loading property for that store and toggle it during the work</li><li><strong>Projections </strong>that are looking at the <strong>store’s</strong> loading property will get automatic updates that can be used to render changes to the UI</li></ul><h4>Projections and External Stores in Sinks</h4><p>As part of the API, all <strong>projections</strong> and <strong>read-only</strong> versions of other <strong>module’s stores</strong> are available in a <strong>sink:</strong></p><pre>sink({ select, getStore }) {<br>  const someProjection = select(&#39;foo.some-projection&#39;).value;<br>  const someStoreValue = getStore(fooStateKey).id;<br>}</pre><blockquote>👉 getStoreis also available in all <strong>projections.</strong></blockquote><h3>Events</h3><blockquote>Everything in <strong>Sink</strong> is tied together by <strong>broadcasting events</strong>. They are simple plain Objects with a <strong>type </strong>and an optional <strong>payload</strong>.</blockquote><p>Create an <strong>event </strong><em>👇</em></p><pre>import { createEvent, payload } from &#39;sink&#39;;</pre><pre>export const SomethingHappend = createEvent(<br>  &#39;a string that is unique for all events&#39;,<br>  payload&lt;{ foo: &#39;string&#39; }&gt;(),<br>)</pre><p><strong>Broadcast </strong>an <strong>event </strong>From a Vue Component <em>👇</em></p><pre>import sink from &#39;@/sink&#39;;<br>import { SomethingHappened } from &#39;@/foo&#39;;</pre><pre>export default defineComponent({<br>  setup() {<br>    sink.broadcast(SomethingHappened({ foo: &#39;hello world&#39; }));<br>  }<br>});</pre><ul><li>We use the broadcast method from our instance of sink to send that <strong>event </strong>through the channel that all of the <strong>sinks</strong> are tapped into</li></ul><p><strong>Broadcast </strong>an <strong>event </strong>from a <strong>sink </strong><em>👇</em></p><pre>import { createSink } from &#39;sink&#39;;<br>import { SomePageLoaded, SomethingHappened } from &#39;@/foo&#39;;</pre><pre>export const someFooSink = createSink({<br>  sources: [SomePageLoaded],<br>  sink({ broadcast }) {<br>    broadcast(SomethingHappened({ foo: &#39;hello world&#39; }));<br>  },<br>});</pre><ul><li>broadcast here functions exactly the same as it does via sink.broadcast</li><li><strong>Broadcasting </strong>from a <strong>sink </strong>can be useful if you need to signal that an operation has succeeded or failed</li><li><strong>Broadcasting </strong>an <strong>event </strong>from a <strong>sink </strong>is entirely optional</li></ul><h3>Unit Testing</h3><blockquote>As a valuable part of any project, I attempted to make unit testing <strong>sinks </strong>and <strong>projections </strong>convenient by exposing an API.</blockquote><blockquote>While not fancy, I think this approach lends itself really well to shipping solid features… if you can encapsulate and isolate the majority of your business logic to simple functions that can be tested it feels like a big win.</blockquote><h4>Unit Testing a Sink with Jest</h4><pre>import { someFooSink } from &#39;./sinks&#39;;</pre><pre>describe(&#39;someFooSink&#39;, () =&gt; {<br>  describe(&#39;when it gets an event&#39;, () =&gt; {<br>    it(&#39;should increment bar by 1&#39;, () =&gt; {<br>      const store = { bar: 0 };</pre><pre>      someFooSink.sink({ store });</pre><pre>      expect(store.bar).toBe(1);<br>    })<br>  })<br>})</pre><h4>Unit Testing a Projection</h4><pre>import { someProjection } from &#39;./projections&#39;;</pre><pre>describe(&#39;someProjection&#39;, () =&gt; {<br>  it(&#39;should return a full name&#39;, () =&gt; {<br>    const store = {<br>      firstName: &#39;Jason&#39;,<br>      lastName: &#39;Awbrey&#39;,<br>    };<br>    <br>    const actual = someProjection.projection({ store });</pre><pre>    expect(actual).toBe(&#39;Jason Awbrey&#39;);<br>  })<br>})</pre><h3>Concluding Thoughts</h3><h4>The Codebase</h4><p>A lot of what enables <strong>sink</strong> to function is made possible by the Vue Composition and Reactive APIs, using such pieces as:</p><ul><li><a href="https://v3.vuejs.org/api/basic-reactivity.html#reactive">reactive</a></li><li><a href="https://v3.vuejs.org/api/computed-watch-api.html#computed">computed</a></li><li><a href="https://v3.vuejs.org/api/composition-api.html#provide-inject">provide/inject</a></li></ul><p>I also use an <a href="https://rxjs.dev/guide/subject">RxJS Subject</a> to help support event broadcasting and registering callbacks, and it makes up a very small portion of the code.</p><p>Another very helpful utility is <a href="https://github.com/cartant/ts-action">ts-action</a>, which helps craft the events.</p><p>The rest is just the <strong>Sink</strong> code that glues it all together, and it’s fairly minimal since we lean heavily into the native Vue APIs.</p><h4>How to Install Sink</h4><blockquote>Update 6/14/21 — I am now slowly working on open sourcing this project.</blockquote><blockquote>You can follow along (if the videos are still up) at <a href="https://www.twitch.tv/jsonberry">Twitch @ jsonberry</a></blockquote><blockquote>When it’s ready it’ll be in <a href="https://www.npmjs.com/package/state-sink">NPM as state-sink</a></blockquote><blockquote>Update 8/4/22 — Definitely not working on this right now, but it’s already been iterated on and working in production for a couple of years. Will make a new post sometime with the updated stuff! I’m not working on open sourcing it at this time.</blockquote><p>That’s not an option yet. I haven’t set aside time to fully open source the library. If there was somehow a spike of interest in moving it into the OS world then I’d see about finding time for it 😸</p><p>For an open source version I would want to target multiple frameworks so that the API could remain consistent and I could bring it into any JavaScript framework that I work with.</p><p>We’re <a href="https://en.wikipedia.org/wiki/Eating_your_own_dog_food">dogfooding</a> it extensively on our team and that’s going well, and if we can budget resources for open source contributions then I would hopefully target introducing the library to the public.</p><p>Outside of that… I really just wanted to show that this stuff is possible mostly with just using the native Vue APIs and contribute to the conversations that are happening in the front-end space relative to reactive approaches to state management.</p><p>Blog posts are never done.</p><p>Later nerds 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=175b216a63fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NgRx — Cherry Picking the Meta]]></title>
            <link>https://medium.com/angular-in-depth/ngrx-cherry-picking-the-meta-30869953e929?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/30869953e929</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Fri, 05 Apr 2019 07:01:00 GMT</pubDate>
            <atom:updated>2020-04-29T21:14:13.842Z</atom:updated>
            <content:encoded><![CDATA[<h3>NgRx — Cherry Picking the Meta</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8yoBLZUdyckACi9z5Uheg.jpeg" /><figcaption>Photo of cherries by <a href="https://unsplash.com/photos/w5Z_lEWYirI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clem Onojeghuo</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*Kk2sSuGhwMG8Tfuq.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>This post is an amalgamation of techniques shared by the NgRx community, with just a step beyond the introductory nature of most of the great posts out there. Here are some of the things it will cover:</p><ul><li>Action dispatches based upon navigation</li><li>Fetching data and handling errors</li><li>Gating Action dispatches <em>(Skip unnecessary API calls)</em></li><li>Call State Reducers and Triggers <em>(Handling Loading and Erroring States)</em></li><li>Entity Detection <em>(This thing loaded?)</em></li></ul><p>Here are the various libraries that are utilized:</p><ul><li>@nrwl/nx — <a href="https://nx.dev/guides/misc-data-persistence">DataPersistence.navigation, fetch</a></li><li>@ngrx — <a href="https://ngrx.io/docs">store, router-store, effects, entity</a></li></ul><p>Usage of the libraries and helper utilities will be showcased first. This is so we can get a feel for the developer ergonomics that the techniques help accomplish, and then we’ll follow up with some implementation details.</p><blockquote><strong>Deep details of setup and what each library does will be skipped</strong>, and there is a list of learning resources and docs in the conclusion.</blockquote><h3>The Base Reducer</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c651b5d17c3fc7ac4ba60c2ca36fc382/href">https://medium.com/media/c651b5d17c3fc7ac4ba60c2ca36fc382/href</a></iframe><p>What can we extrapolate from looking at that ☝️reducer?</p><ul><li>There is a probably a top level state key called movies</li><li>There are <strong>CRUD</strong> helpers and a normalized storage mechanism available via <a href="https://ngrx.io/guide/entity">@ngrx/entity</a> for movies</li><li>When movies are loaded, they’re set in the state tree</li><li>We start with some initialCallState, whatever that is…</li></ul><blockquote>Our application is handling loading and erroring states for movies, <strong>it’s just not obvious yet</strong>.</blockquote><p>When we need to handle <strong>CRUD</strong> scenarios for a movie in the state tree we interact with that <strong>base reducer</strong> as we normally would, and we let a callStateReducer handle loading and erroring states.</p><p>Here👇 is what the state tree would be initially:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNLvzaOGQgGvGNpu1j4-dw.png" /></figure><p>When we navigate to the movies route an action will be dispatched and an API call will be made. The call state will reflect that an API call is in progress for a batch 👇 of movies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*qBecgVoc0CldMRZa-lQKEA.png" /></figure><p>After the movies are loaded the call state will again signify that it is no longer loading, but it’s 👇 back at a resting state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2lNOqA3D_ILUR-0AczCxA.png" /></figure><h3>The Call State Reducer</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/556ece911a6765f0d14959aef7533649/href">https://medium.com/media/556ece911a6765f0d14959aef7533649/href</a></iframe><p>☝️That is the reducer that gets registered in a feature data access module 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fa461552b86cce1aab8de86aa3c4ac2/href">https://medium.com/media/8fa461552b86cce1aab8de86aa3c4ac2/href</a></iframe><h3>The Call State Triggers</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cde3f41620364a061fe3a50920b55ca8/href">https://medium.com/media/cde3f41620364a061fe3a50920b55ca8/href</a></iframe><p>The baseReducer was passed to the callStateReducer along with these moviesCallStateTriggers. They are responsible for declaring when the call state gets triggered for a change.</p><ul><li>For actions that kick off API calls, add the corresponding action to the appropriate loading collection, add as many as you need</li><li>If the API call was successful and data is loaded into the store, add those corresponding actions to the resting collection</li><li>Follow the same pattern for errors</li></ul><p>Before looking at implementation details for call state we’ll switch to another piece of the puzzle, kicking off Actions and data fetching.</p><h3>Dispatch Actions Upon Navigation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*zwKxRlDw7GonWJy0m1W8Pw.png" /><figcaption>Nrwl — Nx Logo</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f29e402c04d9a12af193e51e46e2192/href">https://medium.com/media/6f29e402c04d9a12af193e51e46e2192/href</a></iframe><p>What can we extrapolate from looking at that ☝️effect?</p><ul><li>The <a href="https://nx.dev/guides/misc-data-persistence">DataPersistence</a> library from <a href="https://nx.dev/">Nrwl Extensions</a> is being used</li><li>The MoviesFeatureShellComponent is setup in the Angular Router, because the DataPersistence navigation helper looks for the component to be routed to, and then executes the run callback</li><li>Work we want to associate with navigation has been separated from the component tree</li></ul><blockquote>Opinion: While ngOnInit is low hanging fruit for kicking off something to occur upon navigation, it introduces unnecessary coupling for our intentions and it’s limiting in comparison to what we get from moving the work into an effect.</blockquote><ul><li>We have access to the ActivatedRouteSnapshot in the run callback, as well as a readonly snapshot of the state tree</li><li>We only dispatch an Action to request all movies<strong> if none are loaded</strong>, mitigating redundant API calls</li></ul><blockquote>Note: This gating technique is meant as an example — be sure to adjust your gating logic to match your applications needs.</blockquote><p>Here’s what a detail navigation trigger could look like 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad24c4ba7d6d6e992aff229062c7edc2/href">https://medium.com/media/ad24c4ba7d6d6e992aff229062c7edc2/href</a></iframe><h3>Fetch Data and Catch Errors</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2434146e5cd85a90bc80cfd1b22cc8e7/href">https://medium.com/media/2434146e5cd85a90bc80cfd1b22cc8e7/href</a></iframe><p>A few notes here:</p><ul><li>These data fetching effects are being triggered by the output of our navigation effects. Since the data fetching and navigation concerns are separated, we can update what happens for navigation without having to update what happens for data fetching 👏</li><li>The first parameter in the run callback for fetch is an Action, not the ActivatedRouteSnapshot like in the navigation helper</li><li>If an error occurs in run, the onError callback is called and the stream won’t blow up 🚫💥🤘</li></ul><h3>Quick Midway Recap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwXyQYG2ZxpOjxiPJX7tJQ.jpeg" /><figcaption>Photo of leaves and a neon sign that reads “and breathe” by <a href="https://unsplash.com/photos/buymYm3RQ3U?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Max van den Oetelaar</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>What have we covered so far?</p><ul><li>Saved movies into the state tree</li><li>Separated associated navigation logic from the components <em>(get outta here with that!)</em></li><li>Triggered a fetch of movies based upon navigation</li><li>Skipped unnecessary Action dispatches and avoided redundant API calls</li><li>Fetched a batch of movies in a list/summary view</li><li>Utilized the ActivatedRouteSnapshot to fetch a single movie</li><li>Reflected the loading state of an API call in the state tree</li><li>Caught errors from API calls and reflected that in the state tree</li></ul><p>Which pieces are we missing?</p><ul><li>Selecting information from the store to use in our component trees <em>(are we loading? loaded? was there an error? where’s my data?)</em></li><li>Implementation details <em>(moviesDetector, callStateReducer)</em></li></ul><blockquote>We’re also missing connection directly to the view and we’re not covering that in this post. See the resources list in the conclusion for posts that will cover that.</blockquote><h3>Exposing MoviesState Streams via a Facade</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db8fd911f3da83655831d204435b325e/href">https://medium.com/media/db8fd911f3da83655831d204435b325e/href</a></iframe><p>What can we extrapolate from looking at that ☝️facade?</p><ul><li>All the information that we care about for movies is exposed as different Observable streams. The facade can be injected into the component tree and you can pull out what you need</li><li>We’re able to get the movieByRoute$ which means that router information is available at the selector level</li><li>We can communicate loading and erroring states to our component trees effectively for single or batch fetches of movies</li></ul><blockquote>Opinion: Facades are helpful. They can decouple your application from specific state management implementation lock-in, provide an easy-to-reason about API for data in your application, and potentially simplify testing. They’re also a helpful tool for refactoring if you are upgrading an existing app to use NgRx for the first time — do Facades first, then hook them up to a store. They are not required, and won’t always provide enough benefit to justify using the pattern.</blockquote><h3>Enabling the Facade with Selectors</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b7d82efdcd66fec81b7ecd7d69585dd/href">https://medium.com/media/3b7d82efdcd66fec81b7ecd7d69585dd/href</a></iframe><p>What can we extrapolate from looking at these ☝️selectors?</p><ul><li>There is a getCallStateSelectors factory function giving us access to all the callState selectors we care about</li><li>We have router information in the store so it can be used at the selector level, which helps us with the getMovieByRoute selector. This enables us to <strong>treat the router as a source of truth</strong></li><li>We see our moviesDetector again that is helping us determine if a set of movies is loaded — note that it’s being used here at the selector level, and also some saw some usage in our navigation effects</li></ul><h3>Diving into Implementation Details</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SD5oEzo7-q6BXbjzhdhn-Q.jpeg" /><figcaption>Underwater photo of a man diving into a pool by <a href="https://unsplash.com/photos/Vc8jfmzWoFE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Artem Verbo</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Let’s look first at the moviesDetector:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15eb7814da59413e4d3dadf738bc7495/href">https://medium.com/media/15eb7814da59413e4d3dadf738bc7495/href</a></iframe><p>When I say <em>entity detection</em>, I’m referring to the act of checking for the <em>existence</em> of either a single specific entity or a batch, denoted by these types of checks:</p><ul><li><em>allLoaded — batch</em></li><li><em>noneLoaded — batch</em></li><li><em>oneLoaded — single</em></li><li><em>notLoaded — single</em></li></ul><p>You can see that the moviesDetector is still just wrapping around another helper, the entityDetectorMap. You could use the entityDetectorMap, or just the different entity detectors directly, and the purpose of the moviesDetector is to help with type safety and readability.</p><h3>The Entity Detector — Implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcc8b489a439190d29a576c368d92613/href">https://medium.com/media/bcc8b489a439190d29a576c368d92613/href</a></iframe><p>Some of the goals with these entity detector helpers:</p><ul><li>Type safety</li><li>Ergonomic — These should be easy to use, read, and reason about</li><li>Reusability</li></ul><p>Here’s an example for a pageDetector, checking to see if some page information has been loaded:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de438be551110176b68c4b11b44c93f1/href">https://medium.com/media/de438be551110176b68c4b11b44c93f1/href</a></iframe><h3>The Call State Reducer — Implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51b23e567cfe715c2069a6ad73df77bb/href">https://medium.com/media/51b23e567cfe715c2069a6ad73df77bb/href</a></iframe><p>👆That’s the shape and typings for callState, which we extend for slices of state where we want to use the callStateReducer 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/539ef66be63c243044e4600940e14373/href">https://medium.com/media/539ef66be63c243044e4600940e14373/href</a></iframe><p>Here👇 are all of the callStateReducer implementation details:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32771ca1a1452cbf1a88c91d799883ff/href">https://medium.com/media/32771ca1a1452cbf1a88c91d799883ff/href</a></iframe><p>What can we extrapolate from looking at the that ☝️implementation?</p><ul><li>State and Actions are being passed into the callStateReducer just as any other reducer</li><li>It updates state, but only updates state when the call state triggers we set up are present, and only touches the callState</li><li>This reducer is reusable for any number of state slices, lifting the micromanagement of the loading and erroring states out of the base reducers</li><li>The last step is that the base reducer is called, just like NgRx is expecting</li><li>The getCallStateSelectors factory function takes a feature selector and will return selectors for all the different pieces of callState that we would care about</li><li>An error would clear out automatically upon the next fetch / successful load of data</li></ul><h3>Thoughts on Single and Batch</h3><p>I don’t often see a distinction made with loading and erroring states between a single or a batch set of entities being fetched. I make a distinction because it lets me dial in to create very distinct experiences, and I don’t <em>“cross the wires.” </em>When a <em>single</em> entity is being fetched, and the application also happens to fetch a <em>batch</em> of entities, I want those distinct fetching scenarios to be reflected accurately. A <em>single</em> entity being loaded should not signify that a <em>batch</em> of entities finished loading. This helps keep the atomic nature of <a href="https://martinfowler.com/eaaDev/EventSourcing.html">Event Sourcing</a> intact.</p><h3>Thoughts on Gating Techniques</h3><p>Every application can differ in loading expectations, so be sure to gate action dispatches in a way that matches your applications needs.</p><h3>Thoughts on the DataPersistence Library</h3><p>The DataPersistence library is full of helpful stuff, but it’s not required. You can work out the same patterns without it, you’ll just have to implement similar logic that the library is handling for you. It has some nice goodies like Optimistic and Pessimistic update helpers that I did not show off.</p><h3>Conclusion</h3><p>The techniques in this post are what I’ve cherry picked and adapted from the different solutions out there provided by the NgRx community. If they work for you, great! Be sure to adapt them to your needs.</p><blockquote>Example: You might need to gate an API call for an entity based on a summary/detail already being loaded, for which you’d need to adjust the detection strategy that was showcased in this post.</blockquote><p>It’s important to understand that these challenges <em>(loading data, gating API calls, dealing with errors, selecting relevant information, etc)</em> exist regardless of the state management solution or JavaScript framework/ecosystem we’re using. Understanding these challenges and working through solving them can be applied to any number of different projects and tooling, so it’s helpful to become familiar with the problem domain.</p><p>Deriving loading, loaded, and error states outside of storing information in the state tree is entirely possible and some people think that it’s the right way to do it. <a href="https://pentacledev.com/principles/dont-store-what-you-can-derive">Don’t store what you can derive</a>, and make derivations convenient. Do what’s right for your team. I suggest sticking to idiomatic and community driven solutions, they’re good for other people to pick up on and for you to come back to later.</p><p>I intentionally did not go into a lot of error handling other than setting any in callState because what we do with error information is highly dependent on the design of the error handling journey.</p><h3>Check Out Pentacle</h3><p>I put some time into <a href="https://pentacledev.com/">Pentacle</a> this year, which is an aggregate of idiomatic, battle-tested solutions with learning resources about reactive systems and tools like RxJS, Angular, NgRx and more.</p><p>Check out the <a href="https://medium.com/@jason.s.awbrey/introducing-pentacle-a-reactive-web-learning-nexus-f9d872f9c35b">intro post</a> or peek at the currently available <a href="https://pentacledev.com/resources">resources</a>.</p><h3>Read The Docs</h3><ul><li><a href="https://ngrx.io/guide/store">NgRx — Getting Started</a></li><li><a href="https://ngrx.io/guide/effects">NgRx — Effects</a></li><li><a href="https://ngrx.io/guide/router-store">NgRx — Router Store</a></li><li><a href="https://ngrx.io/guide/entity">NgRx — Entity</a></li><li><a href="https://nx.dev/guides/misc-data-persistence">Nx — DataPersistence</a></li><li><a href="https://nx.dev/getting-started/what-is-nx">Nx — What is it?</a> <em>(hint: it’s more than the DataPersistence library)</em></li></ul><h3>Review These Posts</h3><ul><li><a href="https://blog.angularindepth.com/tagged/ngrx">Posts tagged NgRx on Angular In Depth</a> (AiD)</li><li>AiD — <a href="https://blog.angularindepth.com/how-to-start-flying-with-angular-and-ngrx-b18e84d444aa">How to Start Flying with Angular and NgRx</a></li><li>AiD — <a href="https://blog.angularindepth.com/handling-error-states-with-ngrx-6b16f6d12a08">Handling Error States with NgRx</a></li><li>AiD — <a href="https://blog.angularindepth.com/ngrx-how-and-where-to-handle-loading-and-error-states-of-ajax-calls-6613a14f902d">NgRx: How and where to handle loading and error states of AJAX calls?</a></li><li>AiD — <a href="https://blog.angularindepth.com/handle-api-call-state-nicely-445ab37cc9f8">Handle API call state NICELY</a></li><li>AiD — <a href="https://blog.angularindepth.com/handle-api-call-state-nicely-445ab37cc9f8">NgRx: Parameterized selectors</a></li><li><a href="https://medium.com/@thomasburleson_11450/ngrx-facades-better-state-management-82a04b9a1e39">NgRx + Facades: Better State Management</a></li></ul><h3>Follow These People</h3><ul><li><a href="https://twitter.com/brandontroberts">Brandon Roberts</a></li><li><a href="https://twitter.com/MikeRyanDev">Mike Ryan</a></li><li><a href="https://twitter.com/tim_deschryver">Tim Deschryver</a></li><li><a href="https://twitter.com/AlexOkrushko">Alex Okrushko</a></li><li><a href="https://twitter.com/wesgrimes">Wes Grimes</a></li><li><a href="https://twitter.com/FrozenPandaz">Jason Jean</a></li><li><a href="https://twitter.com/ThomasBurleson">Thomas Burleson</a></li><li><a href="https://twitter.com/victorsavkin">Victor Savkin</a></li><li><a href="https://twitter.com/zhaosiyang0909">Siyang Kern Zhao</a></li><li><a href="https://twitter.com/Michael_Hladky">Michael Hladky</a></li><li><a href="https://twitter.com/wardbell">Ward Bell</a></li></ul><p><em>Find me elsewhere as </em><em>@jsonberry on </em><a href="https://twitter.com/jsonberrry"><em>Twitter</em></a><em> and </em><a href="https://github.com/jsonberry"><em>Github</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30869953e929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/ngrx-cherry-picking-the-meta-30869953e929">NgRx — Cherry Picking the Meta</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Pentacle: A Reactive Web Learning Nexus]]></title>
            <link>https://medium.com/@w3ird0h/introducing-pentacle-a-reactive-web-learning-nexus-f9d872f9c35b?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d872f9c35b</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Tue, 05 Mar 2019 20:55:32 GMT</pubDate>
            <atom:updated>2019-10-05T18:13:07.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFRA0fFoCAS7e9k5vs2KOw.jpeg" /><figcaption>Photo of man sitting on chair near desk surrounded with books by <a href="https://unsplash.com/photos/yLpbSjxMpCU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Elijah Hail</a> on <a href="https://unsplash.com/search/photos/studying?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>The pentacle site has been taken down with it’s content to be published later.</blockquote><blockquote>Learning resources have been moved to <a href="https://learnreactive.com/">https://learnreactive.com</a> , this post remains as prior art.</blockquote><blockquote>TL;DR — Want to learn more about what reactive means, or get more knowledge about a tool like RxJS? Check out the <a href="https://pentacledev.com/resources">Resources</a> page of Pentacle for reactive web learning materials</blockquote><p>Reduce the complexity of building web applications.</p><p>That’s the goal of the ideas and techniques discussed on <a href="https://pentacledev.com/">Pentacle</a>. Simplification is achieved through architecture with a mixture of strategies. At the core of this architecture is reactivity, so our focus is Reactive Web Architecture.</p><p>The most used front-end JavaScript frameworks all support this architecture and thrive on it:</p><ul><li>Angular is a <a href="https://blog.nrwl.io/reactive-programming-in-angular-7dcded697e6c">reactive framework</a>.</li><li>React can start to exhibit more reactive behavior via <a href="https://reactjs.org/docs/hooks-intro.html">hooks</a>. Regardless, it supports a reactive architecture.</li><li>Vue is powered by a <a href="https://vuejs.org/v2/guide/reactivity.html">reactivity system</a>.</li></ul><p>Fortunately, a lot of smart people in the community have developed ideas, strategies, and productivity tools that enable us to build with reactivity in mind.</p><p>But if you’re new to these ideas, it can be confusing, frustrating, and overwhelming to get started — like a 5000-piece Lego set that didn’t come with directions! Pentacle can help.</p><h3>On Pentacle you can learn more about</h3><ul><li>Common patterns found in popular front-end JavaScript applications (React, Vue, Angular)</li><li>Reactive Architecture</li><li>Reactive Extensions (RxJS+)</li><li>Object Oriented Design Patterns</li><li>Functional Reactive Programming 😱</li><li>State Management (Redux, NgRx, etc)</li></ul><h3>So that you can build reactive systems that are</h3><ul><li>Robust</li><li>Maintainable</li><li>Extensible</li><li>Performant</li></ul><h3>The Key Ideas</h3><ol><li>Give different types of responsibilities to separate layers of the application.</li><li>Help those layers communicate by using a common language and structure.</li><li>Adopt specific principles to build reactive attributes into a system.</li></ol><h3>Pentacle’s Goals</h3><ol><li>Collect and present idiomatic, battle-tested, community-supported strategies.</li><li>Present <strong>framework agnostic</strong> concepts that can be applied in many different platforms.</li><li>Provide a catalog of learning resources.</li><li>Connect developers with implementations and tools related to reactive web architecture.</li><li>Lead by example. Pentacle is built on these principles, and <a href="https://github.com/jsonberry/pentacle">the code is open source.</a></li><li>Showcase interactive examples of reactive solutions.</li></ol><p>Pentacle will first focus on reactive coding practices and examples from front-end implementations. The goal is to get that right and grow from there.</p><p>As Pentacle grows, there will be room for more variety in tooling and implementations in our examples. For now, these tools will be used as a framework for understanding. They showcase the power of reactive architecture well, so they’re a good place to start:</p><ul><li><a href="https://rxjs.dev/">RxJS</a></li><li><a href="https://angular.io/">Angular</a></li><li><a href="https://ngrx.io/">NgRx</a></li><li><a href="https://nrwl.io/nx/what-is-nx">Nrwl Extensions</a></li><li><a href="https://www.typescriptlang.org/index.html">TypeScript</a></li></ul><p>We look forward to more examples that include these and many other reactive technologies:</p><ul><li><a href="https://reactjs.org/">React</a></li><li><a href="https://vuejs.org/">Vue</a></li><li><a href="https://martinfowler.com/articles/serverless.html">Serverless</a></li><li><a href="https://nodejs.org/en/">Node</a></li><li><a href="https://nestjs.com/">NestJS</a></li><li><a href="https://www.docker.com/">Docker</a></li><li><a href="https://kubernetes.io/">Kubernetes</a></li><li><a href="https://graphql.org/">GraphQL</a></li><li><a href="https://www.haskell.org/">Haskell</a></li><li><a href="https://kafka.apache.org/">Kafka</a></li></ul><h3>Next Steps</h3><ul><li>Check out the <a href="https://pentacledev.com/overview">Overview</a> for a high-level walkthrough of the architecture.</li><li>Browse the <a href="https://pentacledev.com/resources">Resources</a> page for reactive web learning materials.</li><li>Share! The resources and ideas range from introductory to advanced.</li></ul><h3>Conclusion</h3><p>This project was born out of experimentation and a desire to help spread knowledge about the sometimes highly-challenging topic of reactive programming and architecture. There’s a backlog of features to add, plus I have about 300 (and growing) resources in a queue to curate before adding them to the site. I was hoping to deliver more before announcing the site but other exciting things have beckoned more of my attention. I will continue to add features and resources to the site, and if you want to help come visit the <a href="https://github.com/jsonberry/pentacle">repo</a> and add an issue. Some of my favorite resources for learning about reactive architecture have already been added so I figured now is a better time than never to announce the site.</p><p><em>Feedback and collaboration is encouraged! Please share this with people that are struggling to understand what it means to work in a reactive system.</em></p><p><em>The site — </em><a href="https://pentacledev.com/"><em>https://pentacledev.com</em></a></p><p><em>The repo — </em><a href="https://github.com/jsonberry/pentacle"><em>https://github.com/jsonberry/pentacle</em></a></p><p><em>Find me elsewhere as </em><em>@jsonberry on </em><a href="https://twitter.com/jsonberrry"><em>Twitter</em></a><em> and </em><a href="https://github.com/jsonberry"><em>Github</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d872f9c35b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Scroll Position Restoration with RxJS]]></title>
            <link>https://medium.com/angular-in-depth/reactive-scroll-position-restoration-with-rxjs-792577f842c?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/792577f842c</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Thu, 21 Feb 2019 12:35:18 GMT</pubDate>
            <atom:updated>2020-04-29T21:22:22.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*6xRFDBQQI6UsclI_Z4N51A.png" /><figcaption>Time-lapse of road travel by <a href="https://unsplash.com/photos/3d7DTnuNj6E?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pat Kay</a></figcaption></figure><blockquote>This is a reactive Angular solution via RxJS for simple applications that suffer from a common navigation issue. Similar implementations could be done in other frameworks too.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*aKBwIrHDlEZYigx-.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><h3>SPAs Struggle to Restore Scroll Position</h3><p>JavaScript Single Page Applications rely on navigation libraries that use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/History">History API</a> to route through the application. A common issue is that scroll position isn’t as predictable inside of an SPA — scrolling down a page with lots of content and clicking a link places a user half way down on the next page instead of at the top, or when a user hits a back/forward button the last scrolled to position isn’t restored as expected.</p><p>The most popular and modern front end JavaScript frameworks (React, Vue, and Angular) all suffer from this UX issue. Most navigation library authors have left the management of scroll position restoration up to users because the desired experience might need to be personalized for each application.</p><h3>Investigating Angular Options</h3><p>Angular introduced the <a href="https://angular.io/api/router/ExtraOptions#scrollPositionRestoration">scrollPositionRestoration</a> option in the <a href="https://angular.io/api/router/RouterModule">RouterModule</a> to help alleviate the headache of managing scroll position restoration. It works, but it’s hard to make one technique work for all applications, and this solution comes with caveats:</p><blockquote>It only applies to the primary viewport. As such, it won’t record scroll offsets in a secondary route’s scrollable areas.</blockquote><blockquote>It cannot differentiate between navigation events in the primary and secondary router-outlets. As such, it will scroll back to the top of the page even when the primary route has not changed.</blockquote><blockquote>It cannot differentiate between navigation events that change the entire component tree and navigation events that only change a sub-section of the component tree (like a Tabbed Navigation). As such, it will scroll back to the top of the page even if the app doesn’t warrant it.</blockquote><blockquote>It has no inherent understanding of asynchronous data loading. As such, it will often try to restore a scroll offset before the necessary content is available on the page. This is true <strong>even if the data is cached in-memory</strong> and only needs to be applied to the component template. In other words, this really only applies to <strong>truly static data</strong>.</blockquote><p>☝️ <em>From </em><a href="https://twitter.com/BenNadel"><em>Ben Nadel</em></a><em> on </em><a href="https://www.bennadel.com/blog/3534-restoring-and-resetting-the-scroll-position-using-the-navigationstart-event-in-angular-7-0-4.htm"><em>Restoring And Resetting The Scroll Position Using The NavigationStart Event In Angular 7.0.4</em></a></p><p>In the Angular repo issue #24547 <a href="https://github.com/angular/angular/issues/24547">scrollPositionRestoration has several problems</a>, the Angular team has responded to the requests of the community for a more viable solution, but for right now the work is remains unscheduled.</p><h3>Brainstorming a Solution</h3><p>For a simple application the main takeaways are that the <a href="https://angular.io/api/router/ExtraOptions#scrollPositionRestoration">scrollPositionRestoration</a> won’t work well for:</p><ul><li>Content that is loaded in a secondary route to the viewport, like if the app has a fixed header/sidebar</li><li>Content that is loaded asynchronously</li><li>The application has pages that require scrolling to view all the content</li></ul><p>One of my favorite things about working in an Angular application is it’s interoperability with <a href="https://rxjs.dev/">RxJS</a>. Angular is a <a href="https://blog.nrwl.io/reactive-programming-in-angular-7dcded697e6c">reactive framework</a>, so I wanted my solution to be reactive too, and as a reactive solution I want to try and follow these principles:</p><ul><li><a href="https://pentacledev.com/principles/think-of-everything-as-a-stream">Think of Everything as a Stream</a> — We know the <a href="https://angular.io/api/router/Router">Router</a> publishes events of the <strong>navigation cycle</strong> as an <a href="https://rxjs.dev/guide/observable">Observable</a> stream, so we know when navigations starts and ends</li><li><a href="https://pentacledev.com/principles/declare-what-instead-of-how">Declare What Instead of How</a> — We can use <a href="https://rxjs.dev/api?type=function">RxJS operators</a> to declare what we would like to happen with that stream of <a href="https://angular.io/api/router/Router#events">Router events</a> in order to affect the scroll position</li><li><a href="https://pentacledev.com/principles/dont-store-what-you-can-derive">Don’t Store What You Can Derive</a> — We don’t have to micromanage storing information, we don’t need to store anything in a variable outside of a stream, all we need can be tracked in our functional stream</li></ul><h3>Angular Component Setup</h3><pre>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;app-header&gt;&lt;/app-header&gt;<br>    &lt;div&gt;<br>      &lt;app-side-nav&gt;&lt;/app-side-nav&gt;<br>      &lt;main&gt;<br>        &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export default class AppComponent {}</pre><p>All of the applications routes are being projected into the <a href="https://angular.io/guide/router#router-outlet">router-outlet</a>, that’s where our dynamic content shows up. The main element will be scrolled when we scroll through the pages content. If we get a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop">scrollTop</a> of main, we know the Y scroll position of our dynamic content.</p><p>Next we’ll want to inject the <a href="https://angular.io/api/router/Router">Router</a> into the component and subscribe to it’s <a href="https://rxjs.dev/guide/observable">Observable</a> stream of <a href="https://angular.io/api/router/Router#events">events</a>, we’ll do that inside the <a href="https://angular.io/api/core/OnInit">OnInit</a> lifecycle hook. We can also set up the <a href="https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md#what">pipe</a> off of the stream so that we can begin to craft our declarations with <a href="https://rxjs.dev/api?type=function">RxJS operators</a>.</p><pre>import { Component, OnInit } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { Router } from &#39;<a href="http://twitter.com/angular/router">@angular/router</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;app-header&gt;&lt;/app-header&gt;<br>    &lt;div&gt;<br>      &lt;app-side-nav&gt;&lt;/app-side-nav&gt;<br>      &lt;main&gt;<br>        &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export default class AppComponent implements OnInit {<br>  constructor(private router: Router) {}</pre><pre>  ngOnInit() {<br>    this.router.events.pipe(<br>      // RxJS operators go here<br>    ).subscribe()<br>  }<br>}</pre><p>Now we can start crafting our declarative stream with <a href="https://rxjs.dev/api?type=function">RxJS operators</a>.</p><h3>Declaring What to Do With The Events Observable</h3><p>First, we only care about the events <a href="https://angular.io/api/router/NavigationStart">NavigationStart</a> and <a href="https://angular.io/api/router/NavigationEnd">NavigationEnd</a>, so let’s import those and the RxJS operator <a href="https://rxjs.dev/api/operators/filter">filter</a>. This will let us restrict the stream to only let the router events we care about travel through, based upon a predicate we define:</p><pre>import { NavigationEnd, NavigationStart } from &#39;<a href="http://twitter.com/angular/router">@angular/router</a>&#39;;<br>import { filter } from &#39;rxjs/operators&#39;;</pre><pre>this.router.events.pipe(<br>  filter(<br>    event =&gt;<br>      event instanceof NavigationStart ||<br>      event instanceof NavigationEnd,<br>  ),<br>)</pre><p>Next will be the largest of our functions where we’ll derive most of the information we need. We’re going to use the RxJS operator <a href="https://rxjs.dev/api/operators/scan">scan</a>, and we want to model the output of that function so we can utilize TypeScript <a href="https://www.typescriptlang.org/docs/handbook/type-inference.html">type inference</a> further down the stream. Here’s the interface we’ll use:</p><pre>import { Event } from &#39;<a href="http://twitter.com/angular/router">@angular/router</a>&#39;;</pre><pre>interface ScrollPositionRestore {<br>  event: Event;<br>  positions: { [K: number]: number };<br>  trigger: &#39;imperative&#39; | &#39;popstate&#39;;<br>  idToRestore: number;<br>}</pre><p>This is also when we need to capture main&#39;s <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop">scrollTop</a> value. To capture that we’ll use a <a href="https://angular.io/api/core/ViewChild">ViewChild</a> and query for a <a href="https://angular.io/guide/template-syntax#ref-vars">template reference</a>, let’s set that up:</p><pre>import { ElementRef, ViewChild } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;app-header&gt;<br>    &lt;div&gt;<br>      &lt;app-side-nav&gt;&lt;/app-side-nav&gt;<br>      &lt;main #contentArea&gt; // adding a template reference<br>        &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class AppComponent implements OnInit {<br>  <a href="http://twitter.com/ViewChild">@ViewChild</a>(&#39;contentArea&#39;)<br>  private contentArea: ElementRef&lt;HTMLMainElement&gt;;</pre><p>Now for the <a href="https://rxjs.dev/api/operators/scan">scan</a>, which is like a <em>reduce over time.</em></p><pre>import { scan } from &#39;rxjs/operators&#39;;<br><br>scan&lt;Event, ScrollPositionRestore&gt;((acc, event) =&gt; ({</pre><pre>  event, // either NavigationStart or NavigationEnd</pre><pre>  positions: {<br>    ...acc.positions, // Spread out previously tracked positions<br>    ...(event instanceof NavigationStart<br>      ? { // get snapshot of scrollTop before nav cycle finishes<br>          [event.id]: this.contentArea.nativeElement.scrollTop,<br>        }<br>      : {}),<br>  },</pre><pre>  trigger: // the type of nav, link click? back button?<br>    event instanceof NavigationStart<br>      ? event.navigationTrigger<br>      : acc.trigger,</pre><pre>  idToRestore:<br>    // allows us to grab the correct position to restore<br>    (event instanceof NavigationStart &amp;&amp;<br>      event.restoredState &amp;&amp;<br>      event.restoredState.navigationId + 1) ||<br>    acc.idToRestore,</pre><pre>})),</pre><p>A few notes on the decisions made for this operation:</p><ul><li>event — We keep the event to be used in the next step of the stream.</li><li>positions — Accumulated scroll positions are managed automatically by the <a href="https://rxjs.dev/api/operators/scan">scan</a>, and this is when we grab a snapshot of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop">scrollTop</a> before the navigation cycle completes. I chose an Object instead of an Array because it was easier to work with and didn’t require me to manage anything outside of the stream.</li><li>trigger — This will be either imperative or popstate (at least for our simple application). If it’s imperative, the user has clicked a link, and we’ll need to make sure the user is set to the top of the next page. If it’s popstate, the user has clicked a back/forward button in their browser, and we want to restore the correct scroll position.</li><li>idToRestore — Every navigation cycle has an id associated with it. The cycle begins with the <a href="https://angular.io/api/router/NavigationStart">NavigationStart</a> event and for example it could have an { id: 2 }. When we capture the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop">scrollTop</a> it’s associated with that { id: 2 }, but the scrolling the user did was <em>before</em> that navigation cycle begins, so their scroll position is actually for the <em>previous </em>navigation cycle (which had already completed), in this example { id: 1 }. When navigating via a popstate trigger, there is a navigationId in the events <a href="https://angular.io/api/router/NavigationStart#restoredState">restoredState</a> that refers to the correct navigation cycle where the scrolling occurred, but the scroll position is being mapped to the <em>next</em> cycle. Somewhere there needs to be a + or — of 1, and I chose to do a +1 here to match the scroll position with the id it was mapped to.</li></ul><p>That work targeted what we needed to do for a <a href="https://angular.io/api/router/NavigationStart">NavigationStart</a> event. For the next step we only care about the <a href="https://angular.io/api/router/NavigationEnd">NavigationEnd</a> event since we restore scroll position after the navigation cycle completes, and we want to make sure we have a trigger, so let’s use another <a href="https://rxjs.dev/api/operators/filter">filter</a>:</p><pre>filter(<br>  ({ event, trigger }) =&gt; <br>    event instanceof NavigationEnd &amp;&amp; !!trigger,<br>),</pre><p>The last remaining pieces are to set the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop">scrollTop</a> correctly and to make sure that the work is fired at the correct time. We’re dealing with dynamically loaded content and we need to scroll properly after content has been loaded. First let’s see what setting the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop">scrollTop</a> looks like in the subscription block:</p><pre>.subscribe(({ trigger, positions, idToRestore }) =&gt; {<br>  if (trigger === &#39;imperative&#39;) {<br>    this<br>      .contentArea<br>      .nativeElement<br>      .scrollTop = 0;<br>  }</pre><pre>  if (trigger === &#39;popstate&#39;) {<br>    this<br>      .contentArea<br>      .nativeElement<br>      .scrollTop = positions[idToRestore];<br>  }<br>});</pre><p>The final touch is to queue the work correctly with the navigation cycle and the lifecycle’s of the activated route component. We want to scroll <em>after</em> our dynamic view is ready, which would be denoted by the Component <a href="https://angular.io/api/core/AfterViewInit">AfterViewInit</a> lifecycle hook.</p><p>To correctly queue the work we can use the RxJS operator <a href="https://rxjs.dev/api/operators/observeOn">observeOn</a> and pass in the RxJS <a href="https://rxjs.dev/api/index/const/asyncScheduler">asyncScheduler</a> just before the subscription block. This will let the browser event-loop defer execution of the subscription block to the proper time, in our case just after the <a href="https://angular.io/api/core/AfterViewInit">AfterViewInit</a> lifecycle hook:</p><pre>import { asyncScheduler } from &#39;rxjs&#39;;<br>import { observeOn } from &#39;rxjs/operators&#39;;</pre><pre>observeOn(asyncScheduler),</pre><p>You can learn more about the <a href="https://rxjs.dev/api/operators/observeOn">observeOn</a> operator and the <a href="https://rxjs.dev/api/index/const/asyncScheduler">asyncScheduler</a> in <a href="https://twitter.com/El_Extremal">Alexander Poshtaruk</a>’s article <a href="https://blog.angularindepth.com/rxjs-applying-asyncscheduler-as-an-argument-vs-with-observeon-operator-2340af3b6cac">RxJS: applying asyncScheduler as an argument vs with observeOn operator</a>.</p><h3>Putting It All Together</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70daf95adc35255c0852e296ea53816f/href">https://medium.com/media/70daf95adc35255c0852e296ea53816f/href</a></iframe><h3>Conclusion</h3><p>This is by no means a comprehensive solution for all Angular applications, but it’s some low-hanging fruit that should get you started in fixing that bad UX with scroll positions for dynamic content.</p><p>Originally I wanted to pipe the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop">scrollTop</a> value directly into the template, but I had odd issues where that wasn’t working correctly, so I fell back to subscribing to the stream and imperatively setting what I needed to.</p><p>For a solution that covers more complex scenarios check out <a href="https://twitter.com/BenNadel">Ben Nadel</a>’s article on <a href="https://www.bennadel.com/blog/3534-restoring-and-resetting-the-scroll-position-using-the-navigationstart-event-in-angular-7-0-4.htm">Restoring And Resetting The Scroll Position Using The NavigationStart Event In Angular 7.0.4</a>.</p><p>Happy scrolling 🤘</p><p><em>Thanks to </em><a href="https://twitter.com/El_Extremal"><em>Alexander Poshtaruk</em></a><em> and </em><a href="https://twitter.com/maxim_koretskyi"><em>Max Koretskyi</em></a><em> for the support and review, and </em><a href="https://twitter.com/BenNadel"><em>Ben Nadel</em></a><em> for the inspiration.</em></p><p><em>Find me elsewhere as </em><em>@jsonberry on </em><a href="https://twitter.com/jsonberrry"><em>Twitter</em></a><em> and </em><a href="https://github.com/jsonberry"><em>Github</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=792577f842c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/reactive-scroll-position-restoration-with-rxjs-792577f842c">Reactive Scroll Position Restoration with RxJS</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS-Toolkit: Convenient everday RxJS utilities with pipeable operators]]></title>
            <link>https://itnext.io/rxjs-toolkit-convenient-everday-rxjs-utilities-with-pipeable-operators-a3ba09d22cf3?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3ba09d22cf3</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Wed, 09 Jan 2019 01:14:06 GMT</pubDate>
            <atom:updated>2019-10-05T19:06:34.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*vXJ4-TZd2cNfForoLNes1A.png" /></figure><h3>RxJS-Toolkit: Convenient everyday RxJS utilities with pipeable operators</h3><blockquote>rxjs-toolkit is now unmaintained and has been left up as prior art for future inspiration. Note that there are some operators that do not work in IE11. 10/5/19</blockquote><p>This is the beginning of rxjs-toolkit, a small utility library focused on reusability and everyday use, based on custom <a href="https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md">pipeable operators</a>. There’s only a small handful available for now, and more will get added over time.</p><p>Install rxjs-toolkit via your favorite Node package manager:</p><pre>npm i rxjs-toolkit<br>yarn add rxjs-toolkit</pre><p>Here are a few of the operators to get you started:</p><h3>tapLog</h3><p>When it comes to debugging RxJS streams, often one of the best tools is to use the tap operator and log out the signal passing through. In rxjs-toolkit, there’s an operator for that called tapLog.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12ce151be5e09ee583f2b3b8f3dc7491/href">https://medium.com/media/12ce151be5e09ee583f2b3b8f3dc7491/href</a></iframe><h3>ignoreFalsySignals</h3><p>Sometimes an unwantednull or undefined value could get pushed down your Observable stream. We can mitigate those signals with branching logic inside of a map or use a filter operator to only let truthy signals through. Here’s the ignoreFalsySignalsoperator for that situation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28c4b0adba3ca5b722ef2761f951b16b/href">https://medium.com/media/28c4b0adba3ca5b722ef2761f951b16b/href</a></iframe><p>Here’s a more plausible situation, when you have a stream setup from a function that is hitting an API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcc487d2bf4bf260465227d112ff8b2c/href">https://medium.com/media/fcc487d2bf4bf260465227d112ff8b2c/href</a></iframe><p>In the example above we have guaranteed that the signal is not falsy, but we have not guaranteed the truthy existence of signal.foo. We can solve for that with propsAreTruthy.</p><h3>propsAreTruthy</h3><p>When an Object is traveling through a stream sometimes it won’t have a truthy value for a given property. We can use the propsAreTruthy operator to check if all top-level properties are truthy values. If they aren’t, the signal will be mapped to false:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/706e2a5dea5c824d02b5d887074113b4/href">https://medium.com/media/706e2a5dea5c824d02b5d887074113b4/href</a></iframe><p>Instead of the default of checking all top-level properties, specific properties and nested properties can be checked by passing a list of comma separated strings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da4937bc138fbfe565296be4f75ad38b/href">https://medium.com/media/da4937bc138fbfe565296be4f75ad38b/href</a></iframe><h3>Composable: propsAreTruthy + ignoreFalsyValues</h3><p>To make our lives a bit easier, we can use these two helpers together.</p><ul><li>Check for the truthiness of an Object property</li><li>Ignore the signal if the Object property we care about is falsy</li><li>Keep the stream open for the next signal to pass through</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ffac74c9034eb3ab00a32575f52cb54/href">https://medium.com/media/5ffac74c9034eb3ab00a32575f52cb54/href</a></iframe><p>Enjoy! More operators are on the way :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ba09d22cf3" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/rxjs-toolkit-convenient-everday-rxjs-utilities-with-pipeable-operators-a3ba09d22cf3">RxJS-Toolkit: Convenient everday RxJS utilities with pipeable operators</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Console: Adding Nrwl Schematics to an Existing Project]]></title>
            <link>https://medium.com/@w3ird0h/angular-console-adding-nrwl-schematics-to-an-existing-project-1368ba1eb925?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/1368ba1eb925</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nrwl]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Sun, 12 Aug 2018 18:52:41 GMT</pubDate>
            <atom:updated>2018-08-12T18:52:41.911Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TL;DR — The <strong>Angular Console</strong> is in beta, released 8/8/18. You can generate a new project with <strong>@nrwl/schematics</strong> via the Angular Console, or add them via the CLI extensions section to an existing project. Make sure you’re running <strong>npm</strong> as the CLI package manager, and using at least <strong>@angular/cli</strong> ~6.1.0. This <a href="https://github.com/nrwl/nx/issues/701">GitHub issue</a> has been opened about <strong>Nx </strong>upgrades for cli projects that run yarn as the package manager. Scroll for details and a workaround.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGFmlYFwXXj8GcCow8vuiw.png" /><figcaption>Angular Console Empty Recent Projects Page</figcaption></figure><h3>Angular CLI and Schematics</h3><p>The <strong>@angular/cli</strong> is a command line program that helps spin up new Angular projects, as well as supports the developer with generation tools for all the bits and pieces an Angular developer needs.</p><blockquote><a href="https://github.com/angular/angular-cli/tree/master/packages/angular_devkit/schematics">Schematics are generators that transform an existing filesystem. It can create files, refactor existing files, or move files around.</a></blockquote><p>The <strong>@angular/cli</strong> uses the <strong>@angular-devkit/schematics</strong> project to help work it’s magic. With it we can generate and scaffold components, services, modules and more via the command line.</p><h3>Enter Nrwl, Angular Console, and @nrwl/schematics</h3><p>On August 9th, 2018 Nrwl</p><p><a href="https://nrwl.io/"><strong>Nrwl</strong></a> (nar·whal) is a company founded by <a href="https://twitter.com/victorsavkin"><strong>Victor Savkin</strong></a> and <a href="https://twitter.com/jeffbcross"><strong>Jeff Cross</strong></a>, both principal engineers that worked on Angular. Now they aim to <em>“[help] enterprise teams build better with Angular”</em>, through architecture, training, and engineering. The <strong>Nrwl</strong> team are the creators of the <strong>@nrwl/nx</strong> and <strong>@nrwl/schematics</strong> libraries, and the new <a href="https://blog.nrwl.io/angular-console-the-ui-for-the-angular-cli-a5d0924240b7"><strong>Angular Console</strong></a>.</p><blockquote>Nrwl Extensions, or <strong>Nx</strong> for short, is <strong>an extension for the Angular CLI implementing the monorepo-style development</strong>. It is also <strong>a collection of runtime libraries, linters, and code generators</strong> helping large teams build better with Angular</blockquote><p>The <strong>Angular Console</strong> is a UI for the underlying <strong>@angular/cli</strong> tooling. Nrwl’s goal is to make, <em>“…a great tool for developers who are new to Angular or Angular CLI. You can create projects, interact with your editor, run generators and commands, install extensions without ever touching the terminal or having to install any node packages globally.”</em></p><p><strong>@nrwl/schematics</strong> enhance the <strong>@angular/cli</strong> and allow you to work with an <a href="https://nrwl.io/nx">Nx Workspace</a>. An Nx Workspace differs from a default Angular CLI project as <em>“[it’s] designed to help you create and build enterprise-grade Angular applications with proven project structure and pattern”</em>. One example is that <strong>Nx</strong> comes with a schematic for scaffolding out <a href="https://github.com/ngrx/platform">NgRx</a> modules, the goto Angular <a href="https://redux.js.org/">Redux</a>/<a href="https://martinfowler.com/bliki/CQRS.html">CQMR</a> implementation.</p><p>Even if you aren’t working on a large enterprise team, these patterns and tools can be used to help you quickly create a modular Angular application that helps support <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">SRP</a>.</p><h3>Using Angular Console to generate a new project with @nrwl/schematics</h3><p>Spinning up a new project with the <strong>Angular Console </strong>and <strong>Nx</strong> is easy, just create a new project and select the <strong>@nrwl/schematics </strong>during<strong> </strong>setup.</p><blockquote>Using the <strong>@nrwl/schematics</strong> is just an enhancement to the default CLI schematics. All schematics that you’re used to using will be available if you choose <strong>@nrwl/schematics</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F284599903%3Fapp_id%3D122963&amp;dntp=1&amp;url=https%3A%2F%2Fvimeo.com%2F284599903&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F719085648_960.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1242" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/50ff1624c5b1d47355216d80d55f03f3/href">https://medium.com/media/50ff1624c5b1d47355216d80d55f03f3/href</a></iframe><h3>Adding @nrwl/schematics to an existing project</h3><p>If you navigate to the <strong>Generate Code</strong> tab of a project opened in the Angular Console you’ll see a list of schematics available for use. For an existing project that was generated with default CLI schematics, you’ll see these available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VixyUvkY4CE5-XbG-zI9Bw.png" /></figure><p>When we upgrade the project to use <strong>Nx </strong>the <strong>@nrwl/schematics </strong>will become available in the Angular Console, and the project file system architecture will be updated to match an <strong>Nx Workspace</strong>. For reference, here’s what the default file system structure looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*ncXQUWTpeM85YuBiZy3TPg.png" /><figcaption>Default Angular CLI File System Architecture</figcaption></figure><p>To upgrade via the console, navigate to the <strong>Add/Remove CLI Extensions</strong> and follow the flow for adding the <strong>@nrwl/schematics</strong>:</p><blockquote><strong>Tip:</strong> As of 8/12/18, it looks like the upgrade path only supports projects running <strong>@angular/cli</strong> at <strong>6.1.0</strong> or above. Check your package.json and if your project is running anything prior see if you can update the project to use at least 6.1.0 and you should be able to upgrade.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ds69TQysCbl50xZhFrEshg.png" /><figcaption>Upgrading an existing Angular CLI project to use @nrwl/schematics</figcaption></figure><p>Afterward, you’ll now have access to the schematic options like <strong>NgRx</strong> generation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lG_arJ7AEtqMTLkcInlG3A.png" /><figcaption>Angular Console @nrwl/schematics</figcaption></figure><p>Here’s an example of the changes you’d see in the file system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*jxqnX3VqBAJbzBuvqUbfmA.png" /></figure><h3>Issues with Yarn as the CLI Package Manager</h3><p>Some projects run <strong>yarn</strong> as the cli package manager. It’s <a href="https://medium.com/@beeman/using-yarn-with-angular-cli-v6-7f53a7678b93">easy to set up</a> and useful especially if your team is using yarn.</p><p>Typically, you can upgrade an @angular/cli project using this command:</p><pre>ng add @nrwl/schematics</pre><p>Right now that upgrade path seems to be broken if you’ve set your <strong>@angular/cli</strong> package manager to be <strong>yarn</strong>. I’ve opened <a href="https://github.com/nrwl/nx/issues/701">this issue on GitHub</a> so we can hopefully get some clarity and get it fixed or put in a new feature request.</p><h3>Workaround</h3><p>Set your Angular CLI package manager to npm</p><pre>ng config -g cli.packageManager npm</pre><p>Nuke node modules and reinstall via npm</p><pre>rm -rf node_modules &amp;&amp; npm i</pre><p>You can now add the @nrwl/schematics via the Angular Console or via the terminal. After upgrading to using <strong>Nx</strong> I was able to switch back to using yarn as my CLI package manager.</p><blockquote>Note: As of 8/12/18 Angular Console is still in beta, and the NgRx scaffolding seems to be broken, I opened a <a href="https://github.com/nrwl/angular-console/issues/147">Github issue</a> to help track that. Other schematics are working properly :)</blockquote><p>Overall I’m very pleased with the beginning of the Angular Console and I’m excited to help contribute to the project. It’s easily going to fit into my daily Angular work and help my team move quickly.</p><p>Happy scaffolding!</p><p>Jason’s <a href="https://jason-awbrey.com/">website</a> | <a href="https://github.com/jsonberry">github</a> | <a href="https://twitter.com/jsawbrey">twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1368ba1eb925" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everyday JavaScript: Herding Data Using Objects and Arrays Interchangeably]]></title>
            <link>https://medium.com/@w3ird0h/everyday-javascript-herding-data-using-objects-and-arrays-interchangeably-e7d5a0f64a4d?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7d5a0f64a4d</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[junior-developer]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Sun, 05 Aug 2018 02:56:01 GMT</pubDate>
            <atom:updated>2018-08-05T05:09:00.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBqHMUbnNKQQcWLLcI1OEA.jpeg" /></figure><p>We deal with a lot of data when building our JavaScript web applications. Whether it’s a blog, e-commerce site, or a chat app — there’s a lot of data we have to herd, and there’s a few tasks we do over and over again: filtration, transformation, and selection.</p><p>The topic of data structures is vast, and this article will aim to just target some general knowledge that we can use in our everyday JavaScript lives. Performance, readability, and reusability are what we’ll focus on.</p><p>We’re not going to make any assumptions about where this data is coming from or where it’s sitting, but we will assume that we have access to it whenever we need, and that the data has a defined structure.</p><h3>The Object and Array Structure</h3><p>Let’s look at the same set of data, both as an Object and as an Array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8e1ea59eb8d25c204a1f3c5557d4d4b/href">https://medium.com/media/b8e1ea59eb8d25c204a1f3c5557d4d4b/href</a></iframe><p>In the <strong>objectOfBooks</strong> we are using the <strong>id</strong> as the <strong>key</strong>, and each key is assigned to the <strong>value</strong> of a book. The <strong>arrayOfBooks</strong> houses a list of the same books. Both structures look pretty similar, and they contain the exact same data, so let’s look at some key differences.</p><h3>Filtration</h3><p>Often we’ll need to filter through data to only find the items we want based on a <a href="https://stackoverflow.com/questions/3230944/what-does-predicate-mean-in-the-context-of-computer-science/32383037#32383037">predicate</a>. Perhaps we only want books that have more than 150 pages. Let’s see what it could look like to do that with the Object structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cd494dac0100a2dcb1a9efe9de4e266/href">https://medium.com/media/5cd494dac0100a2dcb1a9efe9de4e266/href</a></iframe><p>If we logged <strong>booksWithMoreThan150Pages</strong> to the console, we would see an object logged out that had the keys of <strong>‘222’</strong>, and <strong>‘333’</strong>. Hurray! That wasn’t so bad. Now, here’s what the filtration could look like if it was an Array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98c968834206f80b7b075040646985f3/href">https://medium.com/media/98c968834206f80b7b075040646985f3/href</a></iframe><p>Alright Array, you win this round.</p><h3>Transformation</h3><p>Often we’ll want to only grab bits and pieces of our data. It’s a common practice when we want to display data in a UI, like a list of blog posts or products. The transformation could involve formatting a date, creating a computed property, or shaking out data we don’t need and delivering a structure of data to the UI that makes more sense. Let’s grab only the title and compute the author’s full name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24fc023ce61a044530b7d0756b204b03/href">https://medium.com/media/24fc023ce61a044530b7d0756b204b03/href</a></iframe><p>Alright — let’s see the Array beat that!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0beb02cc90a705f37cec85a805bbbfe4/href">https://medium.com/media/0beb02cc90a705f37cec85a805bbbfe4/href</a></iframe><p>I think we’ll let the Array take this one too.</p><p>Tangentially, when we want to present a lot of items in a view in most front-end JavaScript frameworks like Angular, Vue, or React, we’ll have an easier time using an Array structure — either because they won’t loop over an Object, but they will loop over an Array, or the syntax is just easier to read with the Array. For a deeper dive on iteration check <a href="http://exploringjs.com/es6/ch_iteration.html">Chapter 21: Iterables and iterators</a>, of <a href="https://twitter.com/rauschma">Dr. Axel Rauschmayer</a>’s <a href="http://exploringjs.com/es6/">Exploring ES6</a>.</p><h3>Selection</h3><p>Most data we’ll deal with will have an ID. Let’s see what it would look like to select a book with id <strong>111</strong>. We’ll give the Array a shot first this time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/513e9be42a719e75a4d0331ee7a2a2ac/href">https://medium.com/media/513e9be42a719e75a4d0331ee7a2a2ac/href</a></iframe><p>Hah! Marvelous! A one liner! Alright Object, let’s see what ya got:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43b05f245b6f7a6df75c9a9ae4ed6e0b/href">https://medium.com/media/43b05f245b6f7a6df75c9a9ae4ed6e0b/href</a></iframe><p>That was certainly more simple, even though the Array structure still wasn’t too bad. The important consideration here is the <a href="https://medium.com/javascript-scene/time-complexity-big-o-notation-1a4310c3ee4b">big O notation</a> of the selection. There’s a computational cost associated with running a function, and looping over an Array versus selecting one item by reference in the Object structure takes more time/space to perform. That’s where the Object structure here will shine.</p><p>You’ve got 1,000 items? With an Object that has keys as IDs for the items, it’s a simple selection, and takes the same computational effort every time. With an Array, you’d have to possibly run a function for all 1,000 items. Using the Object structure for selection will give us an <strong>O(1)</strong> relationship, meaning the function will execute in the same amount of time/space every time. With the Array, the relationship looks more like <strong>O(N)</strong>, where <strong>N</strong> is the number of items. Computational execution will grow linearly along with the number of items in the case of the Array, so the Object wins at selection.</p><h3>The Predicament</h3><p>In <a href="https://github.com/papers-we-love/papers-we-love/blob/master/design/out-of-the-tar-pit.pdf">Out of The Tarpit</a>, the authors describe the fundamental complexity of software has to do with how we manage the state of our applications. State, in our case here, is a list of books. State could refer to lots of different things: is your computer on, is it AM or PM, is the user logged in. One of the main arguments of the paper is that not all state is essential for the application to function correctly, and complexity of development can be reduced by deriving information from already declared state.</p><p>State management is a real big topic in the front-end JavaScript community. Angular, React, Vue, and anyone else in the front-end JavaScript framework space, are all dealing with solving the same problem: managing state. In this article we’re talking about how we can <em>derive</em> (filter/transform/select) information from our <em>state</em> (books). The structure of a web application’s state and how we interact with it becomes paramount to the success of the application.</p><p>Where do we go from here? Do we keep our items in an Object structure, or an Array structure? We’ll use them both, and instead of having duplicates of data, we should use the structures interchangeably, for whichever situation we’re in. In essence, we’ll have one structure, and derive from that what we need.</p><h3>A Proposed Solution</h3><p>For wherever the data actually lives, let’s keep it housed as an Object with keys matching to the ID of the item. That way if a user goes to a page, and it’s for “blog post #111”, then we would know the ID they are looking for, and we can do the selection real fast. When it comes time to do a filter, transform, or other looping scenario, let’s transmute the Object to an Array.</p><p>There are a few different ways to do this, and sometimes it’s helpful to have utility functions on hand to transmute on the fly. Here are a couple examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/966021e21d42fdea983dcf06b8e651fa/href">https://medium.com/media/966021e21d42fdea983dcf06b8e651fa/href</a></iframe><p>Here are condensed versions, utilizing arrow functions and spread operators:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b248943681a0b25ba848cb74c5fb970d/href">https://medium.com/media/b248943681a0b25ba848cb74c5fb970d/href</a></iframe><p>Have a different ID property other than <strong>“id”</strong>? No worries, just use something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ea5ff3c4fd8392fe09650c912b25d7a/href">https://medium.com/media/0ea5ff3c4fd8392fe09650c912b25d7a/href</a></iframe><h3>Putting It All Together</h3><p>Using our new utilities, let’s revisit our different scenarios knowing that the source of our data will be in an Object structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18210617074bc6adc739b354e51a0830/href">https://medium.com/media/18210617074bc6adc739b354e51a0830/href</a></iframe><p>Now we have a clear and concise way of switching our Object into an Array. Sometimes we’ll want to consume some data from an API and it will be in the form of an Array. We can change it to an Object using our new utility. Other times we might need to switch back and forth, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d7b50d0863e3624b407af518e13d17e/href">https://medium.com/media/6d7b50d0863e3624b407af518e13d17e/href</a></iframe><p>All this helps us with performance and readability. Next let’s take a look at how we can extend this concept further to take advantage of reusability.</p><h3>Composing the Bits and Pieces</h3><p>We’ll use a <a href="https://medium.com/javascript-scene/higher-order-functions-composing-software-5365cf2cbe99">higher order function</a> technique to help us compose some reusable code, making it easier to filter, transform, and select our data.</p><h3>Reusable Filters</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab190dac850cd5bf55fdd6310cfe4efe/href">https://medium.com/media/ab190dac850cd5bf55fdd6310cfe4efe/href</a></iframe><h3>Reusable Transforms</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0630756d699a0f1029a89f0ff517e040/href">https://medium.com/media/0630756d699a0f1029a89f0ff517e040/href</a></iframe><h3>Reusable Selectors</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feffd0f9ed0469793b0c2f7379e5a2ac/href">https://medium.com/media/feffd0f9ed0469793b0c2f7379e5a2ac/href</a></iframe><h3>Conclusion</h3><p>We can write data structures and interact with them in a way that’s readable, reusable, and performant. This sort of work can take a lot of effort up front, but pays off. It helps us, and it helps the teams we work with too.</p><h3>Resources</h3><p><a href="http://devdocs.io/javascript/global_objects/array/map">http://devdocs.io/javascript/global_objects/array/map</a></p><p><a href="http://devdocs.io/javascript/global_objects/array/reduce">http://devdocs.io/javascript/global_objects/array/reduce</a></p><p><a href="http://devdocs.io/javascript/global_objects/array">http://devdocs.io/javascript/global_objects/array</a></p><p><a href="http://devdocs.io/javascript/global_objects/object">http://devdocs.io/javascript/global_objects/object</a></p><p><a href="http://devdocs.io/javascript/functions/arrow_functions">http://devdocs.io/javascript/functions/arrow_functions</a> (Advanced Syntax)</p><p><a href="http://devdocs.io/javascript/operators/spread_syntax">http://devdocs.io/javascript/operators/spread_syntax</a></p><p><a href="https://medium.com/javascript-scene/time-complexity-big-o-notation-1a4310c3ee4b">https://medium.com/javascript-scene/time-complexity-big-o-notation-1a4310c3ee4b</a></p><p><a href="https://github.com/papers-we-love/papers-we-love/blob/master/design/out-of-the-tar-pit.pdf">https://github.com/papers-we-love/papers-we-love/blob/master/design/out-of-the-tar-pit.pdf</a></p><p><a href="https://medium.com/javascript-scene/higher-order-functions-composing-software-5365cf2cbe99">https://medium.com/javascript-scene/higher-order-functions-composing-software-5365cf2cbe99</a></p><p><a href="http://exploringjs.com/es6/">http://exploringjs.com/es6/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7d5a0f64a4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Life Lessons and Web Development Resources]]></title>
            <link>https://medium.com/@w3ird0h/life-lessons-and-web-development-resources-51adc7bda8ec?source=rss-a2ca7d5c0904------2</link>
            <guid isPermaLink="false">https://medium.com/p/51adc7bda8ec</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[junior-developer]]></category>
            <dc:creator><![CDATA[w3ird0h]]></dc:creator>
            <pubDate>Thu, 02 Aug 2018 06:45:09 GMT</pubDate>
            <atom:updated>2018-08-02T17:31:45.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ql1l1fG4yDkCK1rXBaQiQ.jpeg" /></figure><p>In 6th grade we were supposed to give a presentation. I have absolutely no recollection of what the assignment was, and sadly I don’t remember anyones presentation. What I remember is giving a talk about HTML and CSS, and how I thought it was the coolest shit in the world. I’m 100% sure it went over 99% of the kids heads in that room, the teacher’s too. I was fascinated by computers and the Internet in general, and poking around in that space was a dream. You can tell that I had a lot of friends.</p><p>That was around 1998. There was probably a lot of dev resources out there, but not like there are today. My mom worked for a software company, and I interviewed the devs and grabbed some information out of an HTML or websites for dummies book and put that magical presentation together. Then I think I found computer games and forgot about all that stuff, for awhile.</p><p>It’s now years later than when I was prowling around on a 56k connection, probably just about to defrag my Windows machine. Now I help lead development teams to victory, casting spells of array filters and collecting immutable object runes, combating the evil Scope Creep and usually just making that button a lighter shade of blue.</p><p><strong>I’d be nowhere close to where I’m at today without the help of mentors and people that believed in me.</strong> <strong>They were only part of the equation</strong>. As I have dived into the developer journey, there a few pieces that have aided in my success. One of those things is not college (no fancy-pants degree here). One of those things is obsession, but I can’t give that away! I can just suggest that you follow your heart. You’re the one that’s gonna have to do it.</p><h3>There and Back Again</h3><p>I ran cross country in high school for about a semester. It was a summer, and one full season, and I really had a lot of fun. Minus the vomit, of course. One day our coach pulled us aside after he had surveyed a route we were going to run. We were somewhere-only-God-knows Oregon running a meet hosted by another school. My teammates and I gathered around to hear the juicy tidbits, tips, and wisdom that the coach had to share:</p><blockquote><em>About a mile and a half in there’s a big long hill. You should all start at a good normal pace. When you get to the hill, keep the pace. Some people are going to hit the incline and slow down a bit to trudge up, others are going to keep their pace. When they all get to the top, most of them are going to slow down, take a breather, and rest a bit to gather their strength. What you should do instead when you get to the top of the hill is just push hard into full gear, and pass them.</em></blockquote><p>I never thought that would stick with me for so long, and apply to so many different aspects of my life. There’s this essential quality that I run with, that when things get tough, I keep a pace and push hard at the precipice. Instead of gliding down, I just roll on the increasing momentum, and I end up covering a lot of ground.</p><p>As it relates to technical understanding, this attitude/technique, is the cornerstone to my success in the web development community. Technical aptitude is only part of web development though, but I’ll just focus on this part for right now, since it was the biggest mystery for me. Coupling this with the sea of dev resources I tapped into has me working hand-in-hand with world class UI and UX designers, leading teams, building enterprise level applications from the small prototype to the grandiose. That 11 year old 6th grader would think I do the coolest shit in the world, and it’s magical.</p><h3>Yes, but where are the dev resources?</h3><p>I have spreadsheets on spreadsheets on spreadsheets of resources outlined and categorized. Scribbled notes and highlighted notebooks. Free stuff, paid stuff, stuff from the past, stuff for the future, stuff for now, stuff that’s hot, stuff that’s fun. Blog posts, video courses, YouTube playlists, books. Yeah, that’s right, books. I think at the very least I could share it back with the community, along with my story. I thought it better to just start writing rather than wait for something perfect to present.</p><p>There’s nothing special about any of this, there’s nothing special about my story or my brain. It’s just what I’ve done, and what’s going on for me now. I’ll be curating the resources I’ve used (and ones I’ve yet to dig into), maybe I’ll match them to a timeline of when I went through them, but mostly I’ll make sure they’re presentable and categorized so that others can pick from them as they see fit. They’ll be heavy on the front-end JavaScript side, but there’s a bunch of other stuff too.</p><p>One way to keep the magic alive, and to hold onto what you have, is to give it away, for free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51adc7bda8ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>