<?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 Simone D&#39;Avico on Medium]]></title>
        <description><![CDATA[Stories by Simone D&#39;Avico on Medium]]></description>
        <link>https://medium.com/@sdavico?source=rss-789fbe8fb1f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fROEtMU_454Uqdg5_5tVuA.jpeg</url>
            <title>Stories by Simone D&amp;#39;Avico on Medium</title>
            <link>https://medium.com/@sdavico?source=rss-789fbe8fb1f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 01:34:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sdavico/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[Supercharging our event-sourcing capabilities with Phoenix LiveView]]></title>
            <link>https://medium.com/casavo/supercharging-our-event-sourcing-capabilities-with-phoenix-liveview-c4a9d1d4ab99?source=rss-789fbe8fb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4a9d1d4ab99</guid>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[phoenix-liveview]]></category>
            <category><![CDATA[commanded]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Simone D'Avico]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 08:32:34 GMT</pubDate>
            <atom:updated>2022-07-15T08:32:34.749Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building visual tools to tame event sourcing architecture complexity</h4><p>In this article, I will describe how we have built some custom visual tools to reduce the complexity of working on WORMS, one of Casavo’s internal products built with the CQRS/ES paradigm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6ZhF8iM_VK_s0OVbmzv5g.png" /><figcaption>A few of the system components involved in the lead creation on WORMS</figcaption></figure><h4>Modeling and implementing core subdomains</h4><p>One of the applications we work on in Casavo is WORMS (WORkflow Management System), which encapsulates the <em>acquisition</em> core subdomain. WORMS supports Casavo seller advisors and valuation analysts to track leads for interesting properties to acquire, evaluate them, estimate their profitability, and define an offer to the seller.</p><p>A <em>core subdomain</em> differentiates and gives a competitive advantage to a company over its competitors. By definition, core subdomains are complex and change frequently. The software for a core subdomain should withstand frequent changes to its business logic and provide good auditability and insights into the business processes it implements.</p><p>The inherent complexity of a core subdomain reflects in the software design. Advanced modeling and software architecture techniques are employed to ensure the solution is resilient to frequent changes over time. Two such techniques are <em>Domain-Driven Design</em> and <em>Event Sourcing</em>, which we used to implement WORMS. More specifically, WORMS is a web application built in Elixir on top of Phoenix and Commanded.</p><h4>Commanded for CQRS/ES</h4><p><a href="https://github.com/commanded/commanded">Commanded</a> is a convenient framework to model applications based on CQRS and Event Sourcing. Such architecture helps us implement complicated state transitions and business rules and protect business invariants. On the other side, an event-sourced application has a lot of components that dramatically increase complexity compared to traditional CRUD applications:</p><ul><li>Aggregates receive <em>commands </em>and emit <em>domain</em> <em>events </em>that are stored in the application <em>event store</em>;</li><li><em>Workflows</em> listen to emitted domain events to send commands to aggregates or communicate with external systems;</li><li><em>Projectors</em> listen to emitted domain events to update the application read models;</li><li><em>Process managers</em> coordinate complex business flows</li></ul><figure><img alt="Main entities in commanded libraries — describes the flow of a command through a router to its aggregate, which emits events, which are listened to from process managers and projectors and stored in an event store; process managers generate more commands, while projectors update the read models." src="https://cdn-images-1.medium.com/max/652/0*g04N25e_FUiejCur.png" /><figcaption>Main entities in Commanded, from <a href="https://blog.nootch.net/post/event-sourcing-with-elixir/">this article series</a></figcaption></figure><h4>How can we manage the complexity of the system?</h4><p><em>Observability</em> has always been a cornerstone characteristic of software systems built with Erlang and Elixir; Erlang provides the observer GUI to expose a lot of info about the running system; Phoenix takes this approach further by providing a built-in <a href="https://hexdocs.pm/phoenix_live_dashboard/Phoenix.LiveDashboard.html">LiveDashboard</a>. Even with these tools, getting insights into the status of a Commanded application can be pretty hard.</p><p>Inspired by the tooling of the Elixir ecosystem, we have built a few utility GUIs with Phoenix LiveView that help us tame the complexity of event sourcing and explore the state of the application:</p><ul><li>Event handlers status page</li><li>Aggregate history debugger</li><li>App schema visualizer</li></ul><h4>Event handlers status page</h4><p>A lot of the behavior of the system is implemented through <a href="https://github.com/commanded/commanded/blob/master/guides/Events.md#event-handlers">event handlers</a>. Event handlers are processes that react to domain events to perform several tasks, such as interacting with external systems (e.g., email providers) and sending commands to aggregates.</p><p>Event handlers create a <a href="https://github.com/commanded/eventstore/blob/master/guides/Subscriptions.md#persistent-subscriptions">persistent subscription</a> to the event store, keeping track of the last received and acknowledged event.</p><p>To have a quick overview of how event handlers behave, we built a LiveView page that lists all event handlers and shows the last acknowledged event for each one.</p><figure><img alt="A screenshot of the event handlers status page" src="https://cdn-images-1.medium.com/max/1024/1*w7bIb2gWOCCrSlu6SbFzag.png" /><figcaption>A screenshot of the event handlers status page</figcaption></figure><p>By computing the difference between the total number of emitted events and the offset of the last event seen by each event handler, we can color code each row to see at first glance which event handlers are “stuck” or are slow in processing events.</p><p><strong>N.B:</strong> <em>This is no substitute for having proper monitoring in place!</em> Nevertheless, it is a handy tool.</p><h4>Aggregate history debugger</h4><p>Interactions with a Commanded application are initiated by sending a <em>command </em>to an <a href="https://github.com/commanded/commanded/blob/master/guides/Aggregates.md">aggregate</a>. The aggregate handles the command by emitting one or more <em>domain events </em>and updating its internal state<em>. An aggregate’s state can always be rebuilt from the ground up by reapplying past domain events. </em>In event sourcing, the events act as the strongly consistent single source of truth for the application state.</p><p>Sometimes, we want to check which events have been emitted by a given aggregate. Doing so can be handy to diagnose bugs or to get insights into when specific events occurred.</p><p>While it would be possible to retrieve the list of events for an aggregate by querying the event store database, we wanted a more visual solution. To this end, we built the <em>aggregate history</em> debugger: the page displays the latest leads that have received an update in WORMS and provides a form to search for a given aggregate by its id. Doing so brings up a timeline of emitted events; each can be expanded to read its JSON payload.</p><figure><img alt="A recording of the aggregate history debugger in action, shows a search for a given aggregate id and browse through the timeline of events" src="https://cdn-images-1.medium.com/max/1024/1*6Lrt72Tad3oN-RMqmdB9dQ.gif" /><figcaption>The aggregate history page in action</figcaption></figure><p>The page reads the latest leads from the leads read model:</p><pre>latest_updated_leads = Repo.all(<br>  from l in Lead, <br>  limit: 10, <br>  order_by: [desc: :updated_at]<br>)</pre><p>For the aggregate search, we compute the id for the aggregates event stream and use the <a href="https://github.com/commanded/eventstore/blob/master/guides/Usage.md#reading-from-all-streams">event store API</a> to retrieve it:</p><pre>stream_uuid = &quot;#{aggregate_type}#{aggregate_id}&quot;<br>{:ok, events} = EventStore.read_stream_forward(stream_uuid)</pre><p>The selected aggregate type and aggregate id are synchronized with the page URL query parameters to allow sharing the link for a specific aggregate search.</p><h4>App schema visualizer</h4><p>The app schema allows visualizing relationships between Commanded entities without browsing the codebase. It provides a combo box to select aggregates, commands, events, or event handlers and draws the appropriate graph.</p><figure><img alt="The app schema visualizer in action, shows the graph for the PropertyInformationConfirmed domain event" src="https://cdn-images-1.medium.com/max/1024/1*B8Z1ylAZ5L4fIPW4hMHgUA.gif" /><figcaption>The app schema visualizer in action</figcaption></figure><p>Each entity has a different color coding (inspired by the <a href="https://virtualddd.com/learning-ddd/ddd-crew-eventstorming-glossary-cheat-sheet">EventStorming color coding</a>), and each vertex in the graph can be clicked to inspect the code of the respective Elixir module.</p><p>Having this kind of visualization and exploration tool comes in handy when we need to review what event handlers listen to some particular event, or similar use cases.</p><p>The app schema graph is resolved at compile-time, by matching module name patterns in WORMS codebase and generating a JSON representation of the graph. The LiveView renders the appropriate graph portion for the selected node via a <a href="https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks-via-phx-hook">LiveView client hook</a> that uses the <a href="https://www.npmjs.com/package/vis-network">vis-network</a> npm package to draw the graph.</p><h4>Conclusion</h4><p>Event sourcing is an advanced architecture pattern best suited to implement a core subdomain complexity. Visual tools to visualize the system behavior and the relationships between its components help us tame the complexity as the system grows and evolves. Commanded and LiveView are great technologies that make building on top of their components easy.</p><p>Hopefully, we will soon be able to contribute to open source some of the solutions we implemented so far in our event sourcing journey!</p><h3>Related reads</h3><p>If you want to read more about WORMS:</p><ul><li><a href="https://medium.com/casavo/business-reliability-as-a-cornerstone-of-our-architectural-choices-5a4f9fcde2c4">Business reliability as a cornerstone of our architectural choices</a></li><li><a href="https://medium.com/casavo/from-stair-to-lift-on-why-we-moved-to-a-task-centric-approach-for-our-workflow-management-system-9649c4f44690">From stair to lift: why we moved to a task-centric approach for our workflow management system</a></li><li><a href="https://medium.com/casavo/type-safe-api-without-writing-and-maintaining-them-in-our-cqrs-event-sourcing-application-746c4dcac582">Type-Safe API without writing and maintaining them in our CQRS + Event Sourcing Application</a></li></ul><p>If you want to read more about Domain-Driven Design and CQRS/ES:</p><ul><li><a href="https://www.oreilly.com/library/view/learning-domain-driven-design/9781098100124/">Learning Domain-Driven Design</a></li><li><a href="https://blog.nootch.net/post/event-sourcing-with-elixir/">Event Sourcing with Elixir</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4a9d1d4ab99" width="1" height="1" alt=""><hr><p><a href="https://medium.com/casavo/supercharging-our-event-sourcing-capabilities-with-phoenix-liveview-c4a9d1d4ab99">Supercharging our event-sourcing capabilities with Phoenix LiveView</a> was originally published in <a href="https://medium.com/casavo">Casavo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing XState machines in your React Native app]]></title>
            <link>https://medium.com/welld-tech/testing-xstate-machines-in-your-react-native-app-236fb01bf5b8?source=rss-789fbe8fb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/236fb01bf5b8</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[xstate]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react-navigation]]></category>
            <dc:creator><![CDATA[Simone D'Avico]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 13:41:34 GMT</pubDate>
            <atom:updated>2021-07-15T13:41:34.357Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>This article shows how to test the payment authorisation flow we implemented with XState and React Navigation. We will first test the business logic, and then add some integration-style tests for the navigation screens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyv3vAWYH7qgpCJWGiadCQ.png" /></figure><p><em>This is the third article of a 3 part series — check out the other parts:</em></p><ul><li><em>Part 1: </em><a href="https://medium.com/welld-tech/untangle-complex-flows-in-your-react-native-app-with-xstate-1b11d0b8a91f"><em>Untangle complex flows in your React Native app with XState</em></a></li><li><em>Part 2: </em><a href="https://medium.com/welld-tech/integrate-xstate-with-react-native-and-react-navigation-21ead87391da"><em>Integrate XState with React Native and React Navigation</em></a></li></ul><p>In the first article of this series, we designed a state machine for the payment authorisation flow of a mobile banking app:</p><figure><img alt="The payment authorisation state machine" src="https://cdn-images-1.medium.com/max/1024/0*JmdFB9JnEsgGoHxv.png" /><figcaption>The payment authorisation state machine</figcaption></figure><p>In the second article, we integrated the state machine with React Navigation. The result is a navigation flow that is completely driven by the app state; we watch the state machine&#39;s current state for changes and navigate to the corresponding screen.</p><figure><img alt="The storyboard for the payment authorisation flow" src="https://cdn-images-1.medium.com/max/1024/0*j8p1SFo38Am_LhWC.png" /><figcaption>The storyboard for the payment authorisation flow</figcaption></figure><p>As a bonus, we also split the biometric factor check in its own machine, to keep the code readable and the logic easier to follow.</p><p>At this point, we want to write some tests to ensure it all works as expected. First, we will write some tests for the state machine; after that, we will test that the machine is well integrated with the navigation flow.</p><h3>Approaches to state machine testing</h3><blockquote><em>Given a current state, when some sequence of events occurs, the system under test should be in a certain state and/or exhibit a specific output.</em></blockquote><p>To test the state machine, we will follow the guidelines outlined in the <a href="https://xstate.js.org/docs/guides/testing.html">XState docs</a>. We can approach these tests in different ways:</p><ol><li><em>Testing effects: </em>we assert that given one or more events some side-effect will be executed. This test can be useful to ensure that effects are fired at the desired time, regardless of what are the states of the machine;</li><li><em>Testing pure logic: </em>we assert that a specific state is reached, given an initial state and an event. This kind of test can be useful to ensure we implemented transitions properly;</li><li><em>Testing services: </em>we assert that the machine eventually reaches an expected state, given an initial state and a sequence of events. I find these tests to be especially useful when the machine implements time-driven logic, such as a timeout.</li></ol><h3>Setup</h3><p>The setup for the tests involves mocking the machine <em>services. </em>We do not want to call the implementation of the real services in the tests, as they probably call remote/device’s APIs. Luckily, XState allows configuring a machine instance with a particular set of services. We can exploit this dependency injection mechanism to provide mocks for our tests:</p><pre>machine = paymentAuthorizationMachine<strong>.withConfig({<br>  services: {<br>    checkPrerequisites: /* mock */,<br>    fetchPaymentDetails: /* mock */,<br>    authorizePayment: /* mock */,<br>  }      <br>});</strong></pre><p>Now we can start writing the actual test cases.</p><h3>Testing effects</h3><p>Let’s start by checking that effects are fired as we expect. The strategy is the following:</p><ul><li>we override the service mocks by invoking withConfig, obtaining a new machine instance;</li><li>we interpret the machine, getting back a service, and we start the service;</li><li>we send one or more events, and assert our services were invoked as expected.</li></ul><p>The payment authorisation machine service will check some prerequisites at startup (e.g., a biometric factor must be enrolled in the device); if those are met, the flow will start and the machine will fetch the payment details; otherwise, the machine will end up in a final error state. Let’s write a test case for this scenario. Code speaks louder than words:</p><pre>it(<br>  &quot;should finish with an error state if biometric factor is not enrolled&quot;,<br>  async () =&gt; {<br>    // arrange <br>    const checkPrerequisites = jest.fn(async () =&gt; false);<br>    const machine = paymentAuthorizationMachine.withConfig({<br>      services: {<br>        checkPrerequisites,<br>        ...<br>      }<br>    });</pre><pre>    const paymentAuthService = <strong>interpret</strong>(machine);<br>    paymentAuthService.<strong>start</strong>();</pre><pre>    await waitFor(() =&gt;<br>      expect(checkPrerequisites).toHaveBeenCalled()<br>    );<br> <br>    // assert<br>    expect(<br>      paymentAuthService.state.matches(&quot;prerequisitesNotMet&quot;)<br>    ).toBeTrue();<br>});</pre><p>We configure the machine with a mock that will fail the prerequisites check; we start the service and ensure our mock gets invoked at machine startup; afterwards, we assert to be in the expected final state.</p><p>I am using waitFor from @testing-library/react-native to wait for the async service invocation, but you can also use Jest’s done callback.</p><h3><strong>Testing pure logic</strong></h3><p>The setup for this kind of test is the same as the previous one, but this time we actually send an event for the service. For example, the user can dismiss the authorisation modal at all times, and we want to ensure that this is also possible during the initial prerequisites check:</p><pre>it(<br>  &quot;should finish with a dismissed state if the user dismisses during prerequisites check&quot;,<br>  async () =&gt; {<br>    // arrange <br>    const machine = paymentAuthorizationMachine.withConfig({<br>      services: {<br>        ...<br>      }<br>    });</pre><pre>    const paymentAuthService = <strong>interpret</strong>(machine);<br>    paymentAuthService.<strong>start</strong>();</pre><pre>    // act<br>    paymentAuthService<strong>.send</strong>(&quot;DISMISS&quot;);</pre><pre>    // assert<br>    expect(<br>      paymentAuthService.state.matches(&quot;authorizationDismissed&quot;)<br>    ).toBeTrue();<br>});</pre><h3>Testing timers</h3><p>After successfully fetching the payment details, the user has a limited time to authorise the transaction. After the AUTHORIZATION_EXPIRES delay expires, the machine will transition to a final error state. The expiration time is computed by subtracting the current time from the expiration time returned by the payment details service.</p><p>To test the expiration works as expected we can return a stubbed expiration date from the payment details service, wait for the required amount of time for the authorisation to expire, and check that we are in the desired state:</p><pre>it(<br>  &quot;should finish with an error state if the authorization expires&quot;,<br> async () =&gt; {</pre><pre>    // arrange<br>    const checkPrerequisites = jest.fn(async () =&gt; false);<br>    // make the authorization expire after 1 second<br>    const fetchPaymentDetails = jest.fn(<br>      async () =&gt; ({ expiresOn: addSeconds(new Date(), 1) })<br>    );<br>    const machine = paymentAuthorizationMachine.withConfig({<br>      services: {<br>        checkPrerequisites,<br>        fetchPaymentDetails,<br>        ...<br>      }<br>    });</pre><pre>    const paymentAuthService = <strong>interpret</strong>(machine);<br>    paymentAuthService.<strong>start</strong>();</pre><pre>    jest.runAllTimers();</pre><pre>    // assert<br>    await waitFor(() =&gt; <br>      expect(<br>        paymentAuthService.state.matches(&quot;authorizationExpired&quot;)<br>      ).toBeTrue();<br>    );<br>});</pre><p>These two test cases definitely do not test the machine exhaustively but should give an idea of the approach to use. We can now take a look at how to test the navigation.</p><h3>Testing navigation</h3><p>Even though we <em>*extensively* </em>tested the state machine and we are confident it works, we still need to make sure it is well integrated with the navigation, i.e. when the machine status changes, the navigation changes accordingly.</p><p>To do so, we write integration-style tests that render the whole payment authorization flow navigation stack. We will use testing-library API to simulate user interactions and check what gets rendered on screen. <a href="https://callstack.github.io/react-native-testing-library/docs/react-navigation/">React Native Testing Library docs</a> have a step by step instructions for setting up React Navigation tests.</p><blockquote>N.B: The implementation I shared in the previous blog post is not super easy to test, because we create and configure the machine directly in the PaymentAuthorizationScreen component. We should refactor it to stub the external services more easily; one way to do so is to receive the services as props. I will leave this as an exercise to the reader :)</blockquote><p>Let’s write a test that ensures we see a loading indicator while the prerequisites are being checked and the authorisation is being fetched:</p><pre>describe(&quot;Payment Authorisation Navigation Flow&quot;, () =&gt; {<br>  it(&quot;should render a loading indicator when opened&quot;, async () =&gt; {</pre><pre>     //arrange<br>     const services = { /* machine services stubs */}</pre><pre>     const component = (<br>       <strong>&lt;NavigationContainer&gt;<br>         &lt;PaymentAuthorizationScreen {...services} /&gt;<br>       &lt;/NavigationContainer&gt;</strong><br>     );</pre><pre>     const { queryByRole } = <strong>render</strong>(component);</pre><pre>     // assert<br>     expect(<strong>queryByRole</strong>(&quot;progressbar&quot;)).toBeTruthy();<br>  });<br>});</pre><p>We can also test that we see the correct screen when the authorisation is declined:</p><pre>describe(&quot;Payment Authorisation Navigation Flow&quot;, () =&gt; {<br>  it(&quot;should render a declined message when user declines&quot;, async () =&gt; {</pre><pre>     // arrange    <br>     const services = { /* machine services stubs */}</pre><pre>     const component = (<br>       <strong>&lt;NavigationContainer&gt;<br>         &lt;PaymentAuthorizationScreen {...services} /&gt;<br>       &lt;/NavigationContainer&gt;</strong><br>     );</pre><pre>     const { getByText, queryByText } = <strong>render</strong>(component);</pre><pre>     // wait for authorization fetch<br>     await waitFor(() =&gt;<br>        expect(queryByText(&#39;DISMISS&#39;)).toBeTruthy()<br>     );</pre><pre>     // act<strong><br>     fireEvent.press(getByText(&quot;DISMISS&quot;));</strong></pre><pre>     // assert<br>     await waitFor(() =&gt;<br>       expect(<br>         <strong>queryByText</strong>(&quot;Payment authorization has been declined&quot;)<br>       ).toBeTruthy()<br>     );<br>  });<br>});</pre><p>We can test the whole flow by stubbing the services as needed, and interacting with the screens as a real user would. Neat!</p><h3>Wrapping up</h3><p>In this article, we added tests to the payment authorisation flow. We were able to test the business logic in isolation from the view layer. XState API allowed us to easily configure each test scenario by configuring stubbed services on the machine. In addition, we made sure the business logic is well integrated with the app screen, by writing integration tests that resemble user interactions with the app.</p><h3>Further reading</h3><ul><li><a href="https://xstate-catalogue.com/">XState Catalogue</a>: a collection of interactive, ready to use state machines to drop in your project;</li><li><a href="https://xstate.js.org/docs/">XState docs</a>;</li><li><a href="https://testing-library.com/docs/react-native-testing-library/intro/">React Native Testing Library docs;</a></li><li><a href="https://kentcdodds.com/blog/?q=testing+react">Kent C. Dodds blog</a> has a lot of insightful articles about how to approach testing React apps.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=236fb01bf5b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/welld-tech/testing-xstate-machines-in-your-react-native-app-236fb01bf5b8">Testing XState machines in your React Native app</a> was originally published in <a href="https://medium.com/welld-tech">WellD Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate XState with React Native and React Navigation]]></title>
            <link>https://medium.com/welld-tech/integrate-xstate-with-react-native-and-react-navigation-21ead87391da?source=rss-789fbe8fb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/21ead87391da</guid>
            <category><![CDATA[finite-state-machine]]></category>
            <category><![CDATA[react-navigation-5]]></category>
            <category><![CDATA[xstate]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-navigation]]></category>
            <dc:creator><![CDATA[Simone D'Avico]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 13:43:21 GMT</pubDate>
            <atom:updated>2021-07-15T13:49:44.286Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let app state drive the navigation between screens</h4><p>In this article, I show how to integrate an XState state machine with React Navigation to implement a complete app flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynIRPi6w7Zm4SIgG55gPEw.png" /></figure><p><em>This is the second article of a 3 part series — check out the other parts:</em></p><ul><li><em>Part 1: </em><a href="https://medium.com/welld-tech/untangle-complex-flows-in-your-react-native-app-with-xstate-1b11d0b8a91f"><em>Untangle complex flows in your React Native app with XState</em></a></li><li><em>Part 3: </em><a href="https://medium.com/welld-tech/testing-xstate-machines-in-your-react-native-app-236fb01bf5b8"><em>Testing XState machines in your React Native app</em></a></li></ul><p>In the first article, we imagined a payment authorisation flow for a mobile banking app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*huK2IunjdsC2okKuxbyuGQ.png" /></figure><p>Realising we would have to mix timers, network calls, native API calls and view state if we implemented the screens directly, we abstracted the business logic for the flow in a state machine…</p><figure><img alt="State machine for a payment authorisation flow" src="https://cdn-images-1.medium.com/max/1024/1*GjV0ChcN_wqEZjzvZUeNKQ.png" /><figcaption>You can try the state machine with the <a href="https://xstate.js.org/viz/?gist=f3f56d0db50426017ee8185400f39760">XState Visualizer</a></figcaption></figure><p>…which we implemented with XState (<a href="https://gist.github.com/simonedavico/95427b093537881972aef28d8edbfa1f">gist</a>). Now, we need to actually use the state machine to orchestrate the transition from one screen of the authorisation flow to the next.</p><p>The idea is to watch the current state of the state machine for changes, and navigate to the corresponding screen. The state machine itself will take care of orchestrating side effects related to API calls and the authorisation timer.</p><p>Let’s get our hands dirty!</p><h3>Setup the navigation stack</h3><p>We should start by creating the navigation stack for the screens with <a href="https://reactnavigation.org/">React Navigation</a>:</p><pre>const PaymentAuthorizationStack = <strong>createStackNavigator()</strong>;</pre><pre>function <strong>PaymentAuthorizationScreen</strong>() {<br>  // ...<br>  return (<br>    &lt;PaymentAuthorizationStack.Navigator&gt;<br>      &lt;PaymentAuthorizationStack.Screen<br>        name=<strong>&quot;Start&quot;</strong><br>        component={<strong>StartScreen</strong>}        <br>      /&gt;<br>      &lt;PaymentAuthorizationStack.Screen<br>        name=<strong>&quot;AuthorizationBiometric&quot;</strong><br>        component={<strong>AuthorizationBiometricScreen</strong>}<br>      /&gt;<br>      &lt;PaymentAuthorizationStack.Screen<br>        name=<strong>&quot;PaymentAuthorized&quot;</strong><br>        component={<strong>PaymentAuthorizedScreen</strong>}<br>      /&gt;<br>      &lt;PaymentAuthorizationStack.Screen<br>        name=<strong>&quot;AuthorizationDeclined&quot;</strong><br>        component={<strong>AuthorizationDeclinedScreen</strong>}<br>      /&gt;<br>      &lt;PaymentAuthorizationStack.Screen<br>        name=<strong>&quot;AuthorizationError&quot;</strong><br>        component={<strong>AuthorizationErrorScreen</strong>}<br>      /&gt;<br>    &lt;/PaymentAuthorizationStack.Navigator&gt;<br>  );<br>}</pre><ul><li>StartScreen is the initial screen of the stack; it displays a loading indicator while the machine checks authorisation prerequisites (e.g. biometric factor is enrolled) and fetches the payment details;</li><li>AuthorizationBiometric is the second screen; it handles the keychain access through biometric factor and displays a loading indicator while the payment authorisation is in flight;</li><li>PaymentAuthorized is the final screen of the happy path; it displays a success message;</li><li>AuthorizationDeclined is the screen that gets displayed when the user declines the payment; it displays a call to action to contact the call center of the bank;</li><li>AuthorizationError is a screen that handles the error states in the flow, displaying an error message depending on the case.</li></ul><p>We also need to start the state machine when we enter the payment authorisation stack. XState provides a set of hooks to integrate state machines with React in the @xstate/react package; the useMachine hook interprets the state machine:</p><pre><strong>import { useMachine } from &quot;@xstate/react&quot;;<br></strong>import machine from &quot;../machine&quot;;</pre><pre>function PaymentAuthorizationScreen() {<br>  <strong>const [state, send, service] = useMachine(machine, {<br>    services: {<br>      checkPrerequisites: async () =&gt; {/* ... */},<br>      fetchPaymentDetails: async () =&gt; {/* ... */},<br>      authorizePayment: async () =&gt; {/* ... */},<br>    }<br>  });</strong></pre><pre>  return (<br>    &lt;PaymentAuthorizationStack.Navigator&gt;<br>       ...<br>    &lt;/PaymentAuthorizationStack.Navigator&gt;<br>  );<br>}</pre><p>Notice that we can inject the required services, further decoupling the state machine definition from the actual interpretation. This could be handy if we need to reuse a machine with different service implementations and makes it possible to stub services during tests.</p><p>The useMachine hook returns a 3 element tuple:</p><ol><li>The first element of the tuple is the current state;</li><li>The second element is a callback to send events to the machine, to trigger state transitions;</li><li>The final element is the service returned by XState when interpreting the machine; it will be useful to listen for and react to state transitions.</li></ol><p>We will use this tuple to render the appropriate view depending on the state. To access it more conveniently, we can also wrap the navigation stack in a context:</p><pre><strong>const PaymentAuthMachineContext = React.createContext(null);</strong></pre><pre>function PaymentAuthorizationScreen() {<br>  const authMachine = useMachine(machine, {<br>    services: {<br>      checkPrerequisites: async () =&gt; {/* ... */},<br>      fetchPaymentDetails: async () =&gt; {/* ... */},<br>      authorizePayment: async () =&gt; {/* ... */},<br>    }<br>  });</pre><pre>  return (<br>    <strong>&lt;PaymentAuthMachineContext.Provider value={authMachine}&gt;</strong>      <br>      &lt;PaymentAuthorizationStack.Navigator&gt;<br>        ...<br>      &lt;/PaymentAuthorizationStack.Navigator&gt;<br>    <strong>&lt;/PaymentAuthMachineContext.Provider&gt;</strong>  <br>  );<br>}</pre><h3>Navigate to the next screen when state changes</h3><blockquote>The idea is to watch the current state of the state machine for changes, and navigate to the corresponding screen.</blockquote><p>For some state changes, we want to navigate to a different screen in our stack. For example, if we are in the checkPrerequisites state and the device has no biometric factor enrolled, the state machine will transition to the prerequisitesNotMet state; accordingly, the app should navigate to the AuthorizationError screen with the appropriate error message.</p><p>We can leverage the service returned from the interpreter to listen for state changes:</p><pre>function StartScreen({ navigation }) {<br>  const [state, send, <strong>service</strong>] = useContext(<br>    PaymentAuthorizationMachineContext<br>  );</pre><pre>  useEffect(() =&gt; {    <br><strong>    const subscription = service.subscribe((state) =&gt; {<br>      if (state.matches(&quot;prerequisitesNotMet&quot;)) {<br>        navigation.navigate(<br>          &quot;AuthorizationError&quot;, { <br>            message: &quot;Cannot authorise payments on this device.&quot;,<br>        });<br>      }<br>    }</strong><br>    return subscription.unsubscribe;<br>  }, [service, navigation]);</pre><pre>  return &lt;SafeAreaView&gt;{/* ... */}&lt;/SafeAreaView&gt;<br>}</pre><p>Besides, we probably want to display a loading indicator while asynchronous calls are being resolved; it is enough to derive the loading state from the machine states we consider to be loading:</p><pre>function StartScreen({ navigation }) {<br>  const [<strong>state</strong>, send, service] = useContext(<br>    PaymentAuthorizationMachineContext<br>  );</pre><pre>  // ...useEffect...</pre><pre>  <strong>const isLoading = state.matches(&quot;checkPrerequisites&quot;) <br>    || state.matches(&quot;fetchingPaymentDetails&quot;);</strong></pre><pre>  return (<br>    &lt;SafeAreaView&gt;<br>      {<br>        isLoading<br>          ? &lt;ActivityIndicator animating /&gt;<br>          : &lt;View&gt;{/* ... */}&lt;/View&gt;<br>      }<br>    &lt;/SafeAreaView&gt;<br>  );<br>}</pre><h3>Access the machine’s context</h3><p>Finally, we can access the machine’s <em>context </em>to derive component state from the machine current state. For example, we need to access the expiresOn date to display an expiration timer:</p><pre>function PaymentAuthorizationTimer() {<br>  const [state, send, service] = useContext(<br>    PaymentAuthorizationMachineContext<br>  );<br>  const navigation = useNavigation();</pre><pre>  useEffect(() =&gt; {    <br><strong>    </strong>const subscription = service.subscribe((state) =&gt; {<br>      if (state.matches(&quot;authorizationExpired&quot;)) {<br>        navigation.navigate(<br>          &quot;AuthorizationError&quot;, { <br>            message: &quot;Cannot authorise payments on this device.&quot;,<br>        });<br>      }<br>    }<br>    return subscription.unsubscribe;<br>  }, [service, navigation]);</pre><pre>  <strong>return state.context.expiresOn ? (<br>    &lt;Timer expiresOn={state.context.expiresOn} /&gt;<br>  ) : null;</strong><br>};</pre><p>We not only encapsulate the logic for displaying the timer but also the logic to transition to the AuthorizationError screen when the timer expires. In this way, we can reuse the PaymentAuthorizationTimer in multiple screens without repeating the logic for the navigation in each of them.</p><h3>Putting it all together</h3><p>If you want to play around with a complete implementation, I have published it in a <a href="https://github.com/simonedavico/payment-authorization-flow">GitHub repository</a>. Don’t feel like going through all the setup? I have got you covered, check out this <a href="https://snack.expo.io/@simonedavico/payment-authorization-flow-with-xstate">Expo Snack</a>!</p><p><em>N.B: subscribing to the service to listen for state changes becomes boilerplate-y in the long run. The logic could be encapsulated in a custom hook to mitigate this, but I wanted to keep the example as “bare metal” as possible.</em></p><p><em>Another approach could be to encode the navigations as XState </em><em>actions, and configure them in the second argument of the </em><em>useMachine hook.</em></p><h3>Bonus: divide et impera</h3><blockquote>By leveraging hierarchical states we can create a state machine that can be nested in the original one.</blockquote><p>If you check the code on GitHub, you may notice that the implementation is simple for all but the <a href="https://github.com/simonedavico/payment-authorization-flow/blob/main/paymentauthorization/screens/AuthorizationBiometricScreen.js">AuthorizationBiometricScreen</a>. We are interacting with asynchronous APIs outside of the state machine, and need to fallback to manage the loading/error states with React states and effects. On the other hand, if we add more states to the machine it will become unwieldy and hard to understand.</p><p>We can get back on track by leveraging <a href="https://xstate.js.org/docs/guides/hierarchical.html">hierarchical states</a>, creating a state machine that can be nested in the original one.</p><p>As an example, in the following gist I have modelled a biometric authentication flow where the user can attempt to authenticate at most 3 times:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/050ca373aef02c517b182709444a5aa4/href">https://medium.com/media/050ca373aef02c517b182709444a5aa4/href</a></iframe><p>This state can be nested in the parent state of the original machine:</p><pre>const paymentAuthorizationMachine = Machine({<br>  // ...<br>  paymentDetailsFetched: {<br>    on: {<br>      DISMISS: &quot;authorizationDismissed&quot;,<br>      KEYCHAIN_ACCESS_OK: &quot;authorizingPayment&quot;,<br>      KEYCHAIN_ACCESS_KO: &quot;biometricFactorError&quot;,<br>    },<br>    <strong>// nest the states</strong><br><strong>    ...keychainAccessStates,</strong><br>  }<br>  // ...<br>});</pre><p>Once more, we were able to orchestrate complex business logic in very little declarative code which is completely decoupled from the corresponding screen!</p><h3>Conclusion</h3><p>Integrating XState and React Navigation helps to keep the screens implementation simple.</p><p>Furthermore, we can scale the state machine as it grows by splitting it into nested substates, encapsulating API calls, the logic for retries, and more.</p><p>In the next article, we will test the state machine. I will show that we can easily stub services and verify that the machine behaves as expected. This will allows us to fully focus on the presentation logic when testing the screens.</p><h3>Further reading</h3><ul><li>Reference implementation on <a href="https://github.com/simonedavico/payment-authorization-flow">GitHub</a>;</li><li>Demo <a href="https://snack.expo.io/@simonedavico/payment-authorization-flow-with-xstate">Expo Snack</a>;</li><li><a href="https://medium.com/@mweststrate/ui-as-an-afterthought-26e5d2bb24d6">UI as an afterthought</a> by <a href="https://twitter.com/mweststrate">Michel Weststrate</a>;</li><li><a href="https://xstate.js.org/docs/">XState docs</a>;</li><li><a href="https://medium.com/@DavidKPiano/the-facetime-bug-and-the-dangers-of-implicit-state-machines-a5f0f61bdaa2">The FaceTime Bug and the Dangers of Implicit State Machines</a> by <a href="https://twitter.com/DavidKPiano">David Khourshid</a>;</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21ead87391da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/welld-tech/integrate-xstate-with-react-native-and-react-navigation-21ead87391da">Integrate XState with React Native and React Navigation</a> was originally published in <a href="https://medium.com/welld-tech">WellD Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Untangle complex flows in your React Native app with XState]]></title>
            <link>https://medium.com/welld-tech/untangle-complex-flows-in-your-react-native-app-with-xstate-1b11d0b8a91f?source=rss-789fbe8fb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b11d0b8a91f</guid>
            <category><![CDATA[xstate]]></category>
            <category><![CDATA[finite-state-machine]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Simone D'Avico]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 09:13:04 GMT</pubDate>
            <atom:updated>2021-07-15T13:50:29.446Z</atom:updated>
            <content:encoded><![CDATA[<h4>Decouple business logic and the views with a well-established CS model.</h4><p>In this article, I am describing how we modelled declaratively a complex flow of a banking app by leveraging XState, a JavaScript library to define finite state machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvOTshrv0BotIkhuwIvnDA.png" /></figure><p><em>This is the first article of a 3 part series — check out the other parts:</em></p><ul><li><em>Part 2: </em><a href="https://medium.com/welld-tech/integrate-xstate-with-react-native-and-react-navigation-21ead87391da?source=your_stories_page-------------------------------------"><em>Integrate XState with React Native and React Navigation</em></a></li><li><em>Part 3: </em><a href="https://medium.com/welld-tech/testing-xstate-machines-in-your-react-native-app-236fb01bf5b8"><em>Testing XState machines in your React Native app</em></a></li></ul><p>In the last few months, I have been working on a banking app implemented with React Native.</p><p>The latest feature I implemented is a flow to authorise a payment transaction. It works as follows:</p><ul><li>The user receives a push notification, prompting to authorise a transaction;</li><li>The user taps the notification and verifies the payment information. A timer notifies that the authorisation request will expire after a few minutes;</li><li>Until the expiration, the user can either <strong>accept </strong>or <strong>decline </strong>the transaction;</li><li>If they accept, they will need to authenticate with a biometric factor (e.g., FaceID). At this point, the app will notify the result of the authorisation attempt;</li><li>If they decline, they will see a confirmation message. We also invite the user to contact the bank if they did not recognise the authorisation request.</li></ul><p>It’s easier to grasp by laying out the storyboard for the flow:</p><figure><img alt="A storyboard for the payment authorisation flow" src="https://cdn-images-1.medium.com/max/1024/1*huK2IunjdsC2okKuxbyuGQ.png" /><figcaption>A storyboard for the payment authorisation flow</figcaption></figure><p>The flow gets even more complex if we integrate calls to REST APIs and the device native APIs:</p><ul><li>at step <em>1</em> we must check that the device has an enrolled biometric factor before fetching the payment details;</li><li>at step <em>3B </em>we need to access some data in the Keychain (protected by a biometric factor) and, if that succeeds, call a remote endpoint to authorise the payment.</li></ul><h3>Decoupling screens and business logic</h3><p>I wanted to avoid implementing the business logic for the flow in the React components. Doing so would result in mixing business logic concerns (API calls, native calls, timed expiration) and view layer concerns (loading states, navigation between screens, error messages).</p><p>At this point, I remembered a wonderful article titled <a href="https://medium.com/@mweststrate/ui-as-an-afterthought-26e5d2bb24d6"><em>“UI as an afterthought”</em></a><em>. </em>Instead of starting the implementation from screens and later think of state and data flow, we should actually do the inverse! We can model the state and interactions first, and map it to the UI later.</p><p>This approach brings some advantages: the business logic itself is easier to test, it’s decoupled from the app screens and can be changed without necessarily touching the views.</p><p>My attempt to model the authorisation flow decoupled from the app screens was eye-opening! I realised I was actually designing a finite state machine:</p><figure><img alt="The finite state machine for the payment authorisation flow." src="https://cdn-images-1.medium.com/max/1024/1*GjV0ChcN_wqEZjzvZUeNKQ.png" /><figcaption>The finite state machine for the payment authorisation flow. Notice how states and screens do not have a 1:1 correspondence!</figcaption></figure><p>There are many solutions for modelling finite state machines in JavaScript. I chose XState, as it is very well documented and is extensively advocated by its author, <a href="https://medium.com/u/3b9ee2f9eaa2">David Khourshid</a>.</p><h3>Modelling with XState</h3><p>Describing a state machine with XState requires setting up two objects, passed as arguments to the Machine constructor:</p><ul><li>A <em>machine config</em>:<strong> </strong>we can think of a machine config as a set of <strong>states; </strong>each state has a unique key and a map of <strong>transitions </strong>to other states. A state can be <strong>final (</strong>meaning that no further transition can occur). We also have to specify an <strong>initial state</strong>;</li><li>A set of <em>machine options</em><strong>: </strong>machine options allow to configure some parts of the machine, such as the <strong>services </strong>(e.g. remote APIs) and <strong>delays </strong>(timers) of the machine;</li></ul><p>XState provides the features we need to implement the model we described in a declarative way. We can <strong>invoke services </strong>when entering a state; a <strong>service </strong>is a function that invokes a REST API and returns the Promise for the call:</p><pre><em>// in the machine config</em><br>checkPrerequisites: {<br>  <strong>invoke</strong>: {<br>    id: &#39;checkPrerequistes&#39;,<br>    src: &#39;<strong>checkPrerequisites</strong>&#39;,<br>    onDone: {<br>      target: &#39;fetchingPaymentDetails&#39;,<br>    },<br>    onError: {<br>      target: &#39;prerequisitesNotMet&#39;,<br>    },<br>  },<br>}</pre><pre><em>// in the machine options</em><br>services: {<br>  // we return a Promise here<br>  <strong>checkPrerequisites</strong>: () =&gt; Biometrics.isEnrolled(),<br>  // ...<br>}</pre><p>As we transition between states and invoke services, we can store some state in the machine’s <strong>context </strong>(using XState’s <a href="https://xstate.js.org/docs/guides/context.html#assign-action">assign</a>):</p><pre>fetchingPaymentDetails: {<br>  invoke: {<br>    id: &#39;fetchPaymentDetails&#39;,<br>    src: &#39;fetchPaymentDetails&#39;,<br>    onDone: {<br>      target: &#39;paymentDetailsFetched&#39;,<br>      // fetchPaymentDetails resolves to <br>      // { paymentAuthorizationId, expiresOn }<br>      <strong>actions</strong>: <strong>assign</strong>((ctx, event) =&gt; {<br>        return event.data;<br>      }),<br>    },<br>    onError: {<br>      target: &#39;paymentDetailsError&#39;,<br>    },<br>  },<br>}</pre><p>Finally, we can describe states that expire after a while by setting <strong>delays </strong>on the machine; the XState interpreter will take care of tracking the state timer and transition to the appropriate state when it expires:</p><pre><em>// in the machine config</em><br>paymentDetailsFetched: {<br>  <strong>after</strong>: {<br>    <strong>AUTHORIZATION_EXPIRES</strong>: {<br>      target: &#39;authorizationExpired&#39;,<br>    },<br>  },<br>  // ...<br>}</pre><pre><em>// in the machine options</em><br><strong>delays</strong>: {<br>  <strong>AUTHORIZATION_EXPIRES</strong>: (ctx) =&gt; {<br>    return Math.max(ctx.expiresOn - new Date(), 0);<br>  },<br>  // ...<br>}</pre><p>Putting the above together, this is a complete implementation of the machine we designed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75ced39f086a9b1c08f54aecc91187f4/href">https://medium.com/media/75ced39f086a9b1c08f54aecc91187f4/href</a></iframe><p>Machine options decouple the implementation of services and delays from the machine config — making it possible to plug in different services or stub them for testing. We could also leave out the machine options, and provide them when we actually run the machine.</p><p>If you want to play around with the machine we defined, you can fire up the <strong>XState Visualizer, </strong>an interactive tool to visualise state machines. Try to trigger the possible transitions, or change the implementation of the services to end up in different final states! You can find the machine we implemented at <a href="https://xstate.js.org/viz/?gist=f3f56d0db50426017ee8185400f39760">this link</a>.</p><h3>Phew, that’s a wrap for now!</h3><p>In this article, we implemented an application flow with XState, a JavaScript library for defining state machines. We were able to implement the whole flow in a declarative way. We could also postpone thinking about the app screens that will expose the functionality.</p><p>In the next article, we will complete the implementation by integrating the state machine with React Native and React Navigation. I will show how the separation of concerns allows us to keep the screens code minimal and, most of all focused on presenting information to the user.</p><h3>Further reading</h3><ul><li><a href="https://medium.com/@mweststrate/ui-as-an-afterthought-26e5d2bb24d6">UI as an afterthought</a> by <a href="https://twitter.com/mweststrate">Michel Weststrate</a>;</li><li><a href="https://xstate.js.org/docs/">XState docs</a>;</li><li><a href="https://medium.com/@DavidKPiano/the-facetime-bug-and-the-dangers-of-implicit-state-machines-a5f0f61bdaa2">The FaceTime Bug and the Dangers of Implicit State Machines</a> by <a href="https://twitter.com/DavidKPiano">David Khourshid</a>;</li></ul><h3>Notes</h3><ol><li>The pictured finite state machine is not the only way to model the payment authorisation flow. For example, we could have collapsed error states in a single one, and used metadata to distinguish the error; it is a tradeoff in being explicit versus avoiding state explosion.</li><li>The machine options we provide in the gist are just for demonstration purpose; a real implementation would probably call some remote or device API.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b11d0b8a91f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/welld-tech/untangle-complex-flows-in-your-react-native-app-with-xstate-1b11d0b8a91f">Untangle complex flows in your React Native app with XState</a> was originally published in <a href="https://medium.com/welld-tech">WellD Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To PWA or not To PWA? Our latest field experience]]></title>
            <link>https://medium.com/welld-tech/to-pwa-or-not-to-pwa-our-latest-field-experience-db854638406e?source=rss-789fbe8fb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/db854638406e</guid>
            <category><![CDATA[workbox]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Simone D'Avico]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 08:50:39 GMT</pubDate>
            <atom:updated>2019-03-22T08:46:12.538Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago we had the chance to build a mobile application for a major energy distribution company involved in <strong>e-mobility</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqDtl284wjQT7RMUjPH4oQ.jpeg" /></figure><p>The company builds and distributes an e-mobility <strong>management dashboard </strong>integrated with all the major e-charging service vendors, allowing them to control the charging units distributed across the territory, monitor their parameters, manage contracts and provide complex data visualisations.</p><p>The goal was to provide quick access to a restricted set of functionalities of the portal. In particular, we had to provide a way to quickly research the charging units registry of the system for a particular Charging Unit, configure new Charging Units installed on the territory and interact with them via remote commands to test the successful start/stop of a recharge.</p><p>The <strong>challenge</strong> was to help operators complete the intended tasks on a smartphone screen, which is quite different from the information-heavy dashboard they were used to.</p><p>We achieved the goal by designing and implementing a <strong>Progressive Web App </strong>that enables operators to complete configuration tasks with the guidance of a wizard. The app relies on <strong>HTML5</strong> features to reduce the manual work required as much as possible.</p><p>Working on this project has been a particularly rewarding experience for us: we had the possibility to <strong>design the UX</strong> from scratch and also face many interesting technical aspects of implementing a mobile web app.</p><p>With this article, we want to dive into the <strong>tech stack</strong> we adopted, how it empowered us to achieve the desired user experience and ultimately share the lessons we learned along the way.</p><h3>Why building a Progressive Web App?</h3><p>There are many pros that make a PWA a good suit, and many <a href="https://medium.com/javascript-scene/native-apps-are-doomed-ac397148a2c0">articles</a> <a href="https://medium.com/javascript-scene/why-native-apps-really-are-doomed-native-apps-are-doomed-pt-2-e035b43170e9">deeply</a> <a href="https://medium.com/dev-channel/why-progressive-web-apps-vs-native-is-the-wrong-question-to-ask-fb8555addcbb">elaborate</a> <a href="https://developer.mozilla.org/en-US/docs/Web/Apps/Progressive/Advantages">on</a> <a href="https://developers.google.com/web/progressive-web-apps/">these</a>. We want to spot out some of them:</p><ul><li>Thanks to the power of <strong>HTML5</strong>, PWAs have access to <a href="https://whatwebcando.today/">a lot of device hardware and features</a>: geolocation, camera and more can be accessed through standard web APIs. PWAs integrate with the mobile OS to provide a UX similar to that of a native app, enabling push notifications and the possibility to add the app icon to the device home screen;</li><li>A PWA has a <strong>lower friction of distribution</strong> than a native app. We were able to setup as many environments (testing, QA…) as we needed, without having to subscribe to any native app beta distribution platform or program;</li><li>Publishing a new version is as simple as deploying a bunch of static assets, without any approval process; since we leverage our <strong>Kubernetes</strong> cluster for deployments we are able to automate the publishing phase in a <strong>CI pipeline</strong>, and get rolling updates, blue/green deployments and rollbacks for free;</li><li>As a consequence, it is also easier to <strong>link</strong> a PWA (it is just a simple URL), <strong>bookmark</strong> and <strong>access</strong> it from multiple sources.</li></ul><p>This said, PWAs have some limitations (e.g., as of today there is no mechanism to make a PWA the target of an Intent for <a href="https://www.chromestatus.com/feature/5662315307335680">inter-app communication</a>) which is important to be aware of. Luckily, modern browsers support all the features we needed to build a successful mobile Charging Unit configurator!</p><h3>Building a mobile Charging Unit configurator</h3><p>From the very beginning, one of the noteworthy challenges of building this application was to adapt in an effective way the existing feature-rich desktop dashboard to a more constrained mobile environment. In particular, we faced three challenges related to both UX and technical aspects:</p><ol><li>Operators had to be able to search for a particular Charging Unit by using its serial number, which is a <strong>long alphanumeric identifier</strong>; this would have been pretty cumbersome on mobile;</li><li>Operators had to be able to configure a new Charging Unit by filling a lot of information. We needed to make this process as <strong>lean</strong> as possible, presenting the information in a compact way;</li><li>Our implementation would have to take into account volatile mobile devices <strong>network, </strong>which are generally <strong>slower</strong> than desktop devices; we needed to optimise network requests without changing the existing APIs, and be resilient for the cases in which there would be no connectivity.</li></ol><h3>Leveraging mobile capabilities</h3><p>We overcome these issues by leveraging the <strong>device capabilities</strong> as much as possible.</p><p>We wanted a better way to search for an existing Charging Unit than having to input a long serial number. Luckily, each Charging Unit comes with a QR Code which encodes exactly that information! We used the device camera and implemented a <strong>QR Code scanner</strong> that would automatically recognise the Charging Unit.</p><p>We organised the data to input for the configuration in three steps, which were implemented as a guided wizard; we used device features such as <strong>GPS</strong>and integrated the Google Maps API to automatically fill in all location-related information.</p><p>Finally, we wanted our app to be <strong>offline-first</strong>: resilient to flaky networks, able to display at least some feedback when the device went offline, with a caching mechanism to avoid repeating API calls for data that rarely change (such as the list of asset providers, the images of the Charging Unit models and similar resources).</p><h3>The tech to make it happen</h3><p>The PWA is built on top of <a href="https://github.com/facebook/create-react-app">create-react-app</a> v1, which provides a ReactJS + Webpack scaffolding with sensible defaults. For the styling part, we built a micro design system by composing <a href="https://tailwindcss.com/">TailwindCSS</a> classes; we wrote almost 0 lines of CSS and still have a nice and consistent look across the whole application.</p><p>By using <a href="https://github.com/zxing-js/library">zxing-js</a> for the QR Code recognition part we were able to easily integrate serial number decoding with the camera video stream, having only to be careful about excluding unnecessary transitive dependencies from the final build with <a href="https://webpack.js.org/configuration/externals/">some Webpack magic</a> (since zxing-js is an <a href="https://en.wikipedia.org/wiki/Isomorphic_JavaScript">isomorphic library</a> it contains some server-side only dependencies). We encapsulated the QR recognition logic in a dedicated React component, which is lazy-loaded through a <a href="https://github.com/tc39/proposal-dynamic-import">dynamic import</a>, to keep the initial bundle size as small as possible.</p><p>Similarly, we leveraged the <a href="https://whatwebcando.today/geolocation.html"><strong>navigator.geolocation</strong></a> API to retrieve the GPS coordinates, use them in a request to Google Maps API to display a human readable address and a map of the area. As for QR code detection, this code is lazy loaded on demand only when the geolocation feature is activated.</p><p>For offline-first support, in the past we implemented data caching and rehydration with <a href="https://github.com/redux-offline/redux-offline">redux-offline</a> in our previous applications. Unfortunately, its usage clutters the application code with its dedicated redux actions format. Furthermore, it caches only data in the redux store, while we wanted control over potentially every response coming from the network (especially images): we needed a solution that would be <strong>transparent</strong> to the application business logic. This is where service workers come into play.</p><h3>There are only two hard problems in CS: service workers and cache invalidation</h3><p>Citing the Google Developers website,</p><blockquote>a Service Worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction.</blockquote><p>While they enable many features (like push notifications), their core capability is acting as network request interceptor and handler (think of a <strong>in-browser proxy</strong>). By combining the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Cache">Cache API</a>, a service worker can be programmed to <strong>cache</strong> incoming network responses; by intercepting network requests, they can avoid going over the wire by returning immediately a previously cached response.</p><p>This means that a PWA with a service worker can cache all its static assets to make the app usable even in lack of network connectivity, and optimise the number of outgoing requests.</p><p>Even though this opens a whole lot of new scenarios, service workers should be activated with care. A web app with a service worker is not simply a set of documents with remote URIs, but behaves more like a native app: the browser will take extra measures to ensure <strong>data consistency</strong> and <strong>code consistency</strong>. This basically means that the service worker changes the usual behaviour of the browser to ensure that the web app does not break unexpectedly across updates (<a href="https://redfin.engineering/service-workers-break-the-browsers-refresh-button-by-default-here-s-why-56f9417694">this article</a> contains a detailed explanation).</p><p>Among the most unexpected and immediate consequences of this change is the fact that <strong>service workers break the refresh button</strong>! There are <a href="https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68">many ways</a> to work around this issue; their implementation has varying degrees of difficulty, and depending on how the web app is used one will be probably more suitable than the others. Unfortunately, the choice requires an understanding of all of them, and coding the solution by combining several different browser APIs.</p><h3>There is only one hard problem in CS: easy caching strategies</h3><p>After some dig into these issues, we concluded that rolling out a custom service worker implementation would not be sustainable in the long run. So we relied on <a href="https://developers.google.com/web/tools/workbox/">Workbox</a>, a set of service worker libraries provided by Google in their effort to promote PWAs.</p><p>In particular, we leveraged the <a href="https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin">Workbox Webpack Plugin</a>, which can generate a service worker that caches all static files produced by the Webpack build. In addition, the plugin allows to <strong>declaratively</strong> configure the service worker behaviour for additional resources; combined with the <a href="https://developers.google.com/web/tools/workbox/modules/workbox-strategies">Workbox Caching Strategies module</a>, it made possible for us to easily configure the caching behaviour of all API responses. This is how an example configuration looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPRaTYkrUmZEz5hML7ISFQ.png" /><figcaption>Caching the response of /api/cu/models for 1 week</figcaption></figure><p>Here, the <strong>Stale While Revalidate</strong> strategy means that the service worker will immediately return the cached response as long as it is still considered fresh (it has been less than one week since it has been cached). Additionally, it will still issue the network request <strong>in the background</strong> to update the cache.</p><p>There are several other strategies available in Workbox to suit different use cases, such as Network Only, Cache Only, Network First and Cache First.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*czlAna1y4iVHMdWKfiDiIA.png" /><figcaption>The app is ready to work offline as soon as it is loaded for the first time</figcaption></figure><h3>The Platform is the limit</h3><p>Building a full-fledged app with web APIs and have it always available in the browser feels great. By applying advanced patterns and the right tooling, it is possible to achieve a result which comes pretty close to the experience of a native app.</p><p>Yet, <strong>we had some aches</strong> while building our PWA.</p><p>For example, caching and the refresh strategy are not the only problems to take into account when enabling service workers; there are many additional aspects to take into account, such as the <a href="https://github.com/facebook/create-react-app/issues/3613#issuecomment-353467430">service worker relationship with code-split bundles</a>. Even with the help of libraries and frameworks, developers should be fully aware of how their application is working and what are the implications of adopting this technology.</p><p>Furthermore, so far the experience with PWAs is <strong>inconsistent</strong> across mobile operating systems; while for Android the support is pretty great, iOS Safari implemented service workers only recently, and debug/develop capabilities in Safari are not as sophisticated as in Chrome. We also experienced difficulties with the OS behaviour itself, since Safari implements a swipe back gesture that cannot be disabled and makes the implementation of some custom gestures impossible, such as reliably dragging a slider from the right edge of the screen.</p><p>Finally, implementing some UX interactions that are standard on native apps (such as fast scroll views and lists) requires a deep knowledge of javascript, css, the ways the browser interacts with the GPU and also a discrete amount of custom code (see <a href="https://developers.google.com/web/updates/2016/07/infinite-scroller">this virtualised list example</a>).</p><h3>Conclusion</h3><p>Today it’s possible to build great experiences for the mobile web, that are well integrated with the device and respect user expectations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTqCtUU1G94lJ7XVaKg6FQ.png" /><figcaption>Part of the Lighthouse performance assessment for the app, which could be further improved with additional optimisations</figcaption></figure><p>The finished PWA provides an easy to use tool for operators to achieve their goals. Taking only 140 kB on device storage, it is fast and performant even on older devices, thanks to a combination of lazy-loading and service worker caching.</p><h3>Further reading</h3><p>The following paragraph collects some of the link that we found useful in our journey to explore Progressive Web Apps. In addition, we also talked of the struggles of building performant mobile experiences and the state of web APIs for building applications at Frontenders Ticino, slides are available <a href="https://speakerdeck.com/simonedavico/the-pursuit-of-pwappiness">here</a>.</p><ul><li><a href="https://www.pwastats.com/">PWA Stats</a>, a list of stats and news regarding PWAs;</li><li><a href="https://jakearchibald.com/2014/offline-cookbook/">The offline cookbook</a>, containing code recipes for a number of service worker patterns;</li><li>The <a href="https://docs.google.com/document/d/16BJDNhfqMjIvJ3_kR4lklpbliCGpi1dFhCdf7kHOsL8">Workbox Window proposal</a>, an API to make interaction with service workers simpler;</li><li><a href="https://progressivetooling.com/">Progressive Tooling</a>, a list of tools to improve web performance;</li><li><a href="https://developers.google.com/web/updates/2018/05/beyond-spa">PWAs as multi page applications</a>;</li><li><a href="https://ionicframework.com/pwa">Ionic PWA</a>, an Angular PWA Toolkit, and <a href="https://stenciljs.com/">StencilJS</a>, based on web components;</li><li><a href="https://blog.twitter.com/engineering/en_us/topics/open-source/2017/how-we-built-twitter-lite.html">Twitter PWA Case Study</a></li><li><a href="https://formidable.com/work/starbucks-progressive-web-app/">Starbucks PWA Case Study</a></li><li><a href="https://medium.com/@addyosmani/a-tinder-progressive-web-app-performance-case-study-78919d98ece0">Tinder PWA Case Study</a></li><li><a href="https://medium.com/dev-channel/a-pinterest-progressive-web-app-performance-case-study-3bd6ed2e6154">Pinterest PWA Case Study</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db854638406e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/welld-tech/to-pwa-or-not-to-pwa-our-latest-field-experience-db854638406e">To PWA or not To PWA? Our latest field experience</a> was originally published in <a href="https://medium.com/welld-tech">WellD Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>