<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
   
    <title>thebhwgroup.com</title>
   
   <link>https://thebhwgroup.com</link>
   <description>We build web and mobile applications for businesses of all sizes.
</description>
   <language>en-us</language>
   <managingEditor>bhwinfo@thebhwgroup.com</managingEditor>
   <atom:link href="rss" rel="self" type="application/rss+xml" />
   
    
	  <item>
        <title>The Habit Burger Grill App Surpasses 1 Million Downloads</title>
        <link>https://thebhwgroup.com/blog/habit-burger-app-1-million-downloads</link>
		<author>Eileen Bau</author>
		<pubDate>2021-03-01T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/habit-burger-app-1-million-downloads</guid>
		<description><![CDATA[
		   BHW’s mobile application for The Habit Burger Grill recently surpassed a huge milestone - it now has more than 1 million downloads! Let’s take a look back and unpack what made this app so successful. We’ll look at the business factors that influenced our design and development considerations from the beginning, and how those considerations were carefully materialized in the features we built.

{% include full-blog-image.html src="blogs/2020-03-01-habit-burger-app-1-million-downloads/habit-app-customization.png" alt="Habit Burger Mobile App - Customizaion Options" %}

We have worked with Habit for around three years. For those unfamiliar with the restaurant industry, Habit’s CIO Mike Repetti put the app’s performance into context:

{% include full-blog-image.html src="blogs/2020-03-01-habit-burger-app-1-million-downloads/habit-app-quote.png" alt="Quote from Habit CIO" %}

As an app tailored for usage by the general public, this project required that BHW incorporate a wide range of considerations into the design and development processes. The app had to be accessible to users of all kinds of demographics, since The Habit Burger is a popular fast-casual chain that serves customers at 275 locations in 13 states and internationally. Additionally, this app had to be comfortable for users with varying familiarity with technology. We put an incredible amount of effort into making sure that the app could easily guide first-time users while also being accommodating to power users.

{% include full-blog-image.html src="blogs/2020-03-01-habit-burger-app-1-million-downloads/habit-app-cover.png" alt="Several screenshots from the Habit Burger Mobile App" %}

As mentioned earlier, The Habit Burger Grill mobile app has an extremely high Apple app store rating of 4.9/5 stars from 18,300 user reviews.

We attribute this high rating to a number of key considerations that we built into this app from the beginning. We focused particularly on things like ease of first-time use, rapid re-ordering for return users, and thoughtful permissions requests and privacy considerations. We also prioritized ease of item customization so that every customer could tailor their order exactly how they wanted it.

{% include full-blog-image.html src="blogs/2020-03-01-habit-burger-app-1-million-downloads/habit-app-store-comments.png" alt="5 star reviews from app stores" %}

Overall, we paid an extreme attention to detail and to removing any possible rough edges from the app. We designed cohesive systems to catch and fulfill every type of ordering flow we could think of. For example, we even made it possible to change the store you order from, but keep the items in your order and its customizations. Because of this, the Habit app is not limited from things like switching locations.

{% include full-blog-image.html src="blogs/2020-03-01-habit-burger-app-1-million-downloads/habit-app-curbside.png" alt="Habit Burger curbside app screenshots" %}

Post-launch, we also made sure to maintain and improve the life cycle of this app. After some time on the market, many mobile apps of similar size and function experience feature bloat - an occurrence where new features or fixes actually interfere with the basic core function of the app, rather than meaningfully improving the experience. We made sure to avoid feature bloat by thoughtfully refining and introducing new features that do not detract from usability.

Finally, we built in robust error tracking, reporting, and analytics to continually improve the performance, reliability, and usability of the applications. As the app continues to grow, we are able to distill valuable insights and iterate with each update. We are excited to have hit the milestone of 1 million downloads, and can’t wait to see what the future brings.


		]]></description>

    
        <category>mobile</category>
    
        <category>engagement</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>Sprinkles Release Announcement</title>
        <link>https://thebhwgroup.com/blog/sprinkles-cupcakes-release-announcement</link>
		<author>Eileen Bau</author>
		<pubDate>2021-02-28T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/sprinkles-cupcakes-release-announcement</guid>
		<description><![CDATA[
		   {% include full-blog-image.html src="blogs/2020-02-28-sprinkles-cupcakes-release-announcement/sprinkles-blog-hero.jpg" alt="Sprinkles - Responsive Ordering System" %}
Our latest release is with Sprinkles, one of America’s favorite cupcake shops! Check out our work live right now at <a href="https://order.sprinkles.com">the ordering site</a>.

Throughout the whole process from design to development, we worked closely with Sprinkles in order to understand their specific needs, workflows, menu, and customers. During this process, we evaluated the existing in-store and above-store technologies to identify the largest area of need for Sprinkles’ digital properties. We were able to design a solution that significantly improved their web ordering experience without disrupting their existing processes or other existing systems. We also designed our solution in such a way that we can continue to improve their host of digital products in the order of largest benefit.

We designed numerous ordering workflows to optimize ordering for various product types. Two of the most complex product types were for Sprinkles’ Cupcakes by Flavor orders and Sprinkles’ Fill a Box cupcake orders.

Cupcakes by Flavor was designed to make ordering higher quantities just as convenient as lower quantities.

{% include full-blog-image.html src="blogs/2020-02-28-sprinkles-cupcakes-release-announcement/cupcake-by-flavor.gif" alt="Sprinkles - Order Cupcakes by Quantity" %}

This design facilitates easily ordering any flavor in any amount. The clean layout displays each available flavor accompanied by photography, with descriptions available if a user clicks on them. Users can order using the plus and minus buttons, or manually type in a number. This makes ordering any number of any flavor incredibly smooth. The number of cupcakes are always displayed on screen as well, so that the user always has confirmation that their order is being updated with their selections. After selecting cupcakes, users are guided through box selection to make sure their cupcakes are packaged to order.

Cupcakes by Flavor and Fill A Box orders were a balancing act between offering the user as much customization as possible while still making the ordering process easy and intuitive. Below, we’ll unpack the process that went into making the complicated Fill A Box workflow easy for customers to use.

##Research
During the research phase, we explored different User Interfaces and websites where the user had the ability to highly customize the product. We examined products inside and outside of the restaurant industry. From the start, we knew we wanted a visual emphasis on the food and the ability to make it highly personalized.

##Information Architecture
We began with a User Flow to identify the various User Experiences, which helped us gain an understanding of current features and functionality vs. what we needed to build.

{% include full-blog-image.html src="blogs/2020-02-28-sprinkles-cupcakes-release-announcement/sprinkles-ia.png" alt="Sprinkles - Information Architecture Diagram" %}

##Wireframing
We prioritized food-forward ordering and rewarding customization options. To do so, we streamlined the entire ordering process to allow the user to design, customize, and review their order in real-time.

We concluded that the most important thing in the ordering process was to give the user control. To bring this to life, we came up with a user friendly and visually appealing solution. We made sure the user could simultaneously browse cupcake options, add them to a box, and view the final product. We also wanted ordering cupcakes to be an exciting process. Each cupcake pops into the box as the user adds it, in any order desired, and each step comes with more options to customize. Users now have a full visual understanding of exactly what they will receive while also introducing a fun element into the ordering process. We hope that this immersive and exciting online ordering experience will keep customers coming back for more.

{% include full-blog-image.html src="blogs/2020-02-28-sprinkles-cupcakes-release-announcement/ux-flow.jpg" alt="Sprinkles - UX Workflow" %}

First, we started with mobile prototypes. With the mobile-first approach, we were able to fit all functionality and features into less screen real-estate to ensure they would translate to desktop seamlessly. From there, we were able to design for desktop while maximizing parts of the User Interface we wanted more visual emphasis on, such as the final cupcake arrangement. This was an iterative process: by continually prototyping out basic ordering flows in mobile and desktop, we could test the design constantly and resolve potential issues early on, before moving to styling.

##Styling
For design, we wanted to keep it simple: focus on the product. Large, professionally shot photos on a white background showcase what Sprinkles has to offer. For the user to get a more rich experience with ordering cupcakes, we designed the box preview to be isometrically viewed, as if the user was sitting at a table and looking down at their creation.

With this 3D angle and our dynamic cupcake quantity pickers, our ordering system offers an almost tangible quality that a static photo just can’t compete with. By combining photos with pixel-perfect box renderings in Photoshop, we were able to layer transparent PNGs on top of each other, brought to life by our amazing developers.

{% include full-blog-image.html src="blogs/2020-02-28-sprinkles-cupcakes-release-announcement/sprinkles-ipad.gif" alt="Sprinkles - Fill a Box Flow" %}

##Responsive Design
We live in an exciting time for product design where mobile can be just as feature-rich and easy to use as desktop - and that’s what we accomplished with this redesign. We did not compromise any functionality in any breakpoint. As a result, the user can enjoy a fully responsive experience. 


##Administrative System
On the administrative side, we built an easy to use admin system to continually configure and adjust the platform without developer involvement. Sprinkles can now independently update information like store hours, item availability, menu items, and special promotional periods with flexibility and efficiency. We also built in robust analytics to continually refine and monitor the platform.

One of the highlights of the admin system is the custom order scheduling and throttling. Because Sprinkles bakes many of their goods same-day for freshness, they needed a way to quickly communicate and coordinate available supply with projected demand at each individual store. Our system enables Sprinkles to manage and update available quantities and orders in real-time, and behaviors can be configured to respond to custom thresholds, such as automatically disabling more orders for certain time slots once they are filled.

##Conclusion
Sprinkles is now able to fulfill orders in a more efficient manner and update bakeries in real-time. From design to development, we helped transform Sprinkles’ ordering system to give customers the ability to order exactly what they want, how they want, when they want it.
		]]></description>

    
        <category>mobile</category>
    
        <category>engagement</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>React Native with JNI &amp; C</title>
        <link>https://thebhwgroup.com/blog/react-native-jni</link>
		<author>Ross Dixon</author>
		<pubDate>2016-10-03T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/react-native-jni</guid>
		<description><![CDATA[
		   <p><a href="https://facebook.github.io/react-native/">React Native</a> has quickly become our preferred way to write <a href="https://thebhwgroup.com/services/mobile-app-development-company-austin-texas">mobile apps</a>. The ability to write code once and have it run well on both Android and iOS really helps development. But what about when we need to write platform specific, low level code? React Native lets us do that too! Via its Java bridge and JNI, we can run C code on Android (iOS will be covered in a later article) and get the results back in JavaScript.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/blogs/2016-10-3-react-native-jni/react_native.png" 
      alt="The React Native Logo. React Native is a framework for building native apps using React"
      
      
       />
      
  </div>
</div>

<h2>Motivation</h2>

<p>Before doing this, make sure it&#39;s actually something you need to do. We chose to do this early on in the planning phase for <a href="https://thebhwgroup.com/projects/geoballistics">BallisticsARC</a>. The app relies on the JBM Ballistics Library, all of which is written in C. If you&#39;re into competitive shooting or just interested in bullet trajectories and ballistics, you&#39;ve likely heard of JBM. For the many who haven&#39;t, it&#39;s a library that takes a bunch of parameters about current atmosphere, rifle, and bullet characteristics and calculates how much a target shooter must compensate for bullet drop and deviation from wind. We had two options in integrating this into our React Native app, rewrite <em>all of it</em> in JavaScript, or dispatch the already written C code from JavaScript. We chose the latter.</p>

<p>If you&#39;re trying to work with a big C library, using JNI on Android is probably your best bet. If you just want to run some C code for performance or because you&#39;re more comfortable writing C, we would heavily advise against doing so. Getting to C from JavaScript is not computationally cheap. So unless you&#39;re doing enormous computations in C (why are you doing this on a phone?), you&#39;re going to lose any C performance boost with the time it takes to pass data around. However, you may have some tasks that just have to be done in C, in which case your only choice is to run C code. So now that you&#39;ve figured out why you&#39;re executing C, let&#39;s get started.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/blogs/2016-10-3-react-native-jni/geoballistics_android_app.jpg" 
      alt="Screenshots of the Geoballistics React Native Mobile App"
      
      
       />
      
  </div>
</div>

<h2>Setup</h2>

<p>This article assumes that you are at least familiar with React Native, Java, and C and have a working development environment for React Native on Android set up, as <a href="https://facebook.github.io/react-native/docs/getting-started.html">explained in the React Native docs</a>. In addition to having RN set up, you&#39;ll also need to get the <a href="https://developer.android.com/ndk/downloads/index.html">Android NDK (Native Development Kit)</a>. While we have not had an issue using later versions, React Native only supports version 10e, which you may download here.</p>

<ul>
<li>Mac OS X - <a href="http://dl.google.com/android/repository/android-ndk-r10e-darwin-x86_64.zip">http://dl.google.com/android/repository/android-ndk-r10e-darwin-x86_64.zip</a></li>
<li>Linux 64-bit - <a href="http://dl.google.com/android/repository/android-ndk-r10e-linux-x86_64.zip">http://dl.google.com/android/repository/android-ndk-r10e-linux-x86_64.zip</a></li>
<li>Windows 64-bit - <a href="http://dl.google.com/android/repository/android-ndk-r10e-windows-x86_64.zip">http://dl.google.com/android/repository/android-ndk-r10e-windows-x86_64.zip</a></li>
<li>Windows 32-bit - <a href="http://dl.google.com/android/repository/android-ndk-r10e-windows-x86.zip">http://dl.google.com/android/repository/android-ndk-r10e-windows-x86.zip</a></li>
</ul>

<p>In the event RN changes what version of the NDK it relies on, links should be available on their <a href="https://facebook.github.io/react-native/docs/building-from-source">Building from Source</a> page.</p>

<p>Once you&#39;ve downloaded and unzipped the NDK, you need to either set the environment variable <code>ANDROID_NDK</code> to point to the directory it was unzipped to (the one containing the <code>toolchains</code> directory), or add the line <code>ndk.dir=&lt;directory&gt;</code> (replacing <code>&lt;directory&gt;</code> with your NDK&#39;s directory) to <code>android/local.properties</code> (create it if it doesn&#39;t exist) in your React Native project.</p>

<h2>JavaScript to Java</h2>

<p>The first step in running C code from React Native is to run Java code from React Native. If you need further explanation or details on the JS-Java bridge beyond this article, check out React Native&#39;s guide to <a href="https://facebook.github.io/react-native/docs/native-modules-android.html">Native Modules on Android</a>.</p>

<p>We&#39;re going to start simple and write our own Hello World. In the Java src directory of your React Native project <code>android/app/src/main/java/com/thebhwgroup/demo</code> (replacing <code>com/thebhwgroup/demo</code> with your package), create a new file called <code>HelloWorldModule.java</code>.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="c1">//HelloWorldModule.java</span>
<span class="kn">package</span> <span class="n">com</span><span class="o">.</span><span class="na">thebhwgroup</span><span class="o">.</span><span class="na">demo</span><span class="o">;</span> <span class="c1">//replace com.thebhwgroup.demo with the package name in MainApplication.java</span>

<span class="kn">import</span> <span class="nn">com.facebook.react.bridge.Promise</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.facebook.react.bridge.ReactApplicationContext</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.facebook.react.bridge.ReactContextBaseJavaModule</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.facebook.react.bridge.ReactMethod</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">HelloWorldModule</span> <span class="kd">extends</span> <span class="n">ReactContextBaseJavaModule</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="nf">HelloWorldModule</span><span class="o">(</span><span class="n">ReactApplicationContext</span> <span class="n">reactContext</span><span class="o">)</span> <span class="o">{</span>
        <span class="kd">super</span><span class="o">(</span><span class="n">reactContext</span><span class="o">);</span> <span class="c1">//required by React Native</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getName</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="s">&quot;HelloWorld&quot;</span><span class="o">;</span> <span class="c1">//HelloWorld is how this module will be referred to from React Native</span>
    <span class="o">}</span>

    <span class="nd">@ReactMethod</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">helloWorld</span><span class="o">(</span><span class="n">Promise</span> <span class="n">promise</span><span class="o">)</span> <span class="o">{</span> <span class="c1">//this method will be called from JS by React Native</span>
        <span class="n">promise</span><span class="o">.</span><span class="na">resolve</span><span class="o">(</span><span class="s">&quot;Hello World!&quot;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<p>As explained by the comments, the <code>getName()</code> method is used by React Native to identify this module, it will later be referenced as <code>React.NativeModules.HelloWorld</code> in JavaScript. As for <code>helloWorld(Promise)</code>, there are a couple ways to return data from Java to JavaScript. We prefer to use promises as it generally results in easier to read code than callbacks. <code>Promise.resolve()</code> is used on a successful result, <code>Promise.reject()</code> is used in the event of an error or exception. Details can be found in React Native docs.</p>

<p>Before this module can be registered with React Native, it first must be added to a package. Create another file in the same directory as <code>HelloWorldModule.java</code>, and name it <code>MyReactPackage.java</code>.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="c1">//MyReactPackage.java</span>
<span class="kn">package</span> <span class="n">com</span><span class="o">.</span><span class="na">thebhwgroup</span><span class="o">.</span><span class="na">demo</span><span class="o">;</span> <span class="c1">//replace com.thebhwgroup.demo with the package name in MainApplication.java</span>

<span class="kn">import</span> <span class="nn">com.facebook.react.ReactPackage</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.facebook.react.bridge.JavaScriptModule</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.facebook.react.bridge.NativeModule</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.facebook.react.bridge.ReactApplicationContext</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.facebook.react.uimanager.ViewManager</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.util.ArrayList</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Collections</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.List</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyReactPackage</span> <span class="kd">implements</span> <span class="n">ReactPackage</span> <span class="o">{</span>
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">Class</span><span class="o">&lt;?</span> <span class="kd">extends</span> <span class="n">JavaScriptModule</span><span class="o">&gt;&gt;</span> <span class="nf">createJSModules</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">Collections</span><span class="o">.</span><span class="na">emptyList</span><span class="o">();</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">ViewManager</span><span class="o">&gt;</span> <span class="nf">createViewManagers</span><span class="o">(</span><span class="n">ReactApplicationContext</span> <span class="n">reactContext</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">Collections</span><span class="o">.</span><span class="na">emptyList</span><span class="o">();</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">NativeModule</span><span class="o">&gt;</span> <span class="nf">createNativeModules</span><span class="o">(</span><span class="n">ReactApplicationContext</span> <span class="n">reactContext</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">List</span><span class="o">&lt;</span><span class="n">NativeModule</span><span class="o">&gt;</span> <span class="n">modules</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>

        <span class="n">modules</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="nf">HelloWorldModule</span><span class="o">(</span><span class="n">reactContext</span><span class="o">));</span> <span class="c1">//this is where we register our module, and any others we may later add</span>

        <span class="k">return</span> <span class="n">modules</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<p><code>createJSModules()</code> and <code>createViewManagers()</code> are used for other native code aspects in React Native, but have to be implemented here. <code>createNativeModules()</code> is where <code>HelloWorldModule</code> is registered along with any more modules that are created later. Now this package can be registered with React Native. Open <code>MainApplication.java</code> and find the <code>getPackages()</code> method.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="nd">@Override</span>
<span class="kd">protected</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">ReactPackage</span><span class="o">&gt;</span> <span class="nf">getPackages</span><span class="o">()</span> <span class="o">{</span>
    <span class="k">return</span> <span class="n">Arrays</span><span class="o">.&lt;</span><span class="n">ReactPackage</span><span class="o">&gt;</span><span class="n">asList</span><span class="o">(</span>
            <span class="k">new</span> <span class="nf">MainReactPackage</span><span class="o">()</span>
    <span class="o">);</span>
<span class="o">}</span>
</code></pre></div>
<p>Add your package to the list so that it looks like so</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="nd">@Override</span>
<span class="kd">protected</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">ReactPackage</span><span class="o">&gt;</span> <span class="nf">getPackages</span><span class="o">()</span> <span class="o">{</span>
    <span class="k">return</span> <span class="n">Arrays</span><span class="o">.&lt;</span><span class="n">ReactPackage</span><span class="o">&gt;</span><span class="n">asList</span><span class="o">(</span>
            <span class="k">new</span> <span class="nf">MainReactPackage</span><span class="o">(),</span>
            <span class="k">new</span> <span class="nf">MyReactPackage</span><span class="o">()</span>
    <span class="o">);</span>
<span class="o">}</span>
</code></pre></div>
<p>That&#39;s it for Java! (for now) Back to where you&#39;ve put your JavaScript code, make a new file <code>HelloWorld.js</code>.</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="c1">//HelloWorld.js</span>
<span class="s1">&#39;use strict&#39;</span>
<span class="kr">import</span> <span class="p">{</span> <span class="nx">NativeModules</span> <span class="p">}</span> <span class="nx">from</span> <span class="s1">&#39;react-native&#39;</span><span class="p">;</span>
<span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nx">NativeModules</span><span class="p">.</span><span class="nx">HelloWorld</span><span class="p">;</span>
</code></pre></div>
<p>This file is now ready for import. If you wanted to change <code>NativeModules.HelloWorld</code> to something else, you would change the string returned from <code>getName()</code> in <code>HelloWorldModule.java</code>. Now, in a file where you want to use this, add the following.</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kr">import</span> <span class="nx">HelloWorld</span> <span class="nx">from</span> <span class="s1">&#39;./HelloWorld&#39;</span><span class="p">;</span> <span class="c1">//HelloWorld.js file we just made</span>

<span class="p">...</span>

<span class="nx">async</span> <span class="nx">helloWorld</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">try</span> <span class="p">{</span>
        <span class="kd">let</span> <span class="nx">helloWorldStr</span> <span class="o">=</span> <span class="nx">await</span> <span class="nx">HelloWorld</span><span class="p">.</span><span class="nx">helloWorld</span><span class="p">();</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">helloWorldStr</span><span class="p">);</span>
    <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="nx">e</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<p>You can put this <code>helloWorld()</code> function anywhere you would put another function, like inside the component in which it will be used. Also if you&#39;re using lambda functions, the first line can instead be written as <code>helloWorld = async () =&gt; {</code><br>
Note that since we&#39;re using promises (and not callbacks) <code>HelloWorld.helloWorld()</code> must either be called in an async function with await, or called in a normal function with the resulting variable calling <code>Promise.then()</code> or <code>Promise.all()</code>. If this is a new syntax to you there are a couple guides overviewing async/await, and MDN has documentation on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">Promises</a>.<br>
Add a call to this function somewhere in your code and run your app on an Android emulator or phone. You should see <code>Hello World!</code> printed out in the Android logcat (run <code>adb logcat -s ReactNativeJS</code> to filter only React Native logs).</p>

<p>Now that we&#39;re successfully calling Java code from JavaScript, it&#39;s time to bring our Hello World down to C.</p>

<h2>Java to C</h2>

<h3>C</h3>

<p>Calling C code from Java is enabled with the Java Native Interface (JNI). To start, make a new directory in your project at <code>android/app/src/main/jni</code> and add the following files to it.</p>

<h4>Android.mk</h4>
<div class="highlight"><pre><code class="language-makefile" data-lang="makefile"><span class="nv">LOCAL_SRC_FILES</span> <span class="o">:=</span> hello_world.c
<span class="nv">LOCAL_MODULE</span> <span class="o">:=</span> hello_world_jni
</code></pre></div>
<h4>Application.mk</h4>
<div class="highlight"><pre><code class="language-makefile" data-lang="makefile"><span class="nv">APP_ABI</span> <span class="o">:=</span> all
</code></pre></div>
<h4>hello_world.c</h4>
<div class="highlight"><pre><code class="language-c" data-lang="c"><span class="c1">//hello_world.c</span>
<span class="cp">#include &lt;jni.h&gt;</span>

<span class="n">jstring</span> <span class="nf">Java_com_thebhwgroup_demo_HelloWorldModule_helloWorldJNI</span><span class="p">(</span><span class="n">JNIEnv</span><span class="o">*</span> <span class="n">env</span><span class="p">,</span> <span class="n">jobject</span> <span class="n">thiz</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">return</span> <span class="p">(</span><span class="o">*</span><span class="n">env</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">NewStringUTF</span><span class="p">(</span><span class="n">env</span><span class="p">,</span> <span class="s">&quot;Hello World!&quot;</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div>
<p><code>Android.mk</code> tells Android what source files to compile, for now only <code>hello_world.c</code>, and what to name our module, <code>hello_world_jni</code>. <code>Application.mk</code> instructs Android to build against all supported architectures. For more explanation on these, see the Android documentation for <a href="https://developer.android.com/ndk/guides/android_mk.html">Android.mk</a> and <a href="https://developer.android.com/ndk/guides/application_mk.html">Application.mk</a>.</p>

<p><code>hello_world.c</code> might look a little odd at first, but this is how JNI looks. C functions called by JNI return JNI types, an explanation of which can be found in the <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html">JNI Spec</a>. Generally, putting &quot;j&quot; before a C/Java type will get you the JNI type, and in some cases they&#39;re nothing more than a typedef. A <code>jdouble</code> for example is defined by <code>typedef double jdouble;</code></p>

<p>The name of the function is very specific, it must start with Java, followed by the package name, the class, and the function name within the class. So there is a Java function, in our com.thebhwgroup.demo package, in the HelloWorldModule class, called helloWorldJNI. All functions called via JNI must take a <code>JNIEnv*</code> and <code>jobject</code> as their first two parameters, the <code>JNIEnv*</code> is a &quot;pointer to a structure storing all JNI function pointers&quot; and is how JNI functions are called in C.</p>

<p>Our C function itself is simple, it&#39;s just calling a JNI function to make a <code>jstring</code> that can be converted to a <code>java.lang.String</code> by JNI. Note that it is both called from <code>env</code> and passed <code>env</code> as its first parameter, every JNI function is called this way. Details on JNI functions can also be found in the <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html">JNI Spec</a>.</p>

<h3>Java</h3>

<p>This module now needs to be loaded and called from Java code. Open the app <code>build.gradle</code> file, found at <code>android/app/build.gradle</code>. Under the <code>ndk</code> section, add the line <code>moduleName &quot;hello_world_jni&quot;</code> (as named in Android.mk) along with the <code>ldLibs</code> and <code>cFlags</code> lines so that it looks like so.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ndk</span> <span class="o">{</span>
    <span class="n">abiFilters</span> <span class="s">&quot;armeabi-v7a&quot;</span><span class="o">,</span> <span class="s">&quot;x86&quot;</span>
    <span class="n">moduleName</span> <span class="s">&quot;hello_world_jni&quot;</span>
    <span class="n">ldLibs</span> <span class="s">&quot;log&quot;</span>
    <span class="n">cFlags</span> <span class="s">&quot;-std=c99&quot;</span>
<span class="o">}</span>
</code></pre></div>
<p>This instructs gradle to build and include the module with your app. The <code>ldLibs</code> line links the Android logging library allowing us to make logcat calls from C (something we&#39;ll do later), and the <code>cFlags</code> enables C99 features. Next open <code>HelloWorldModule.java</code> and add the following <code>static</code> block right after the class definition.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">HelloWorldModule</span> <span class="kd">extends</span> <span class="n">ReactContextBaseJavaModule</span> <span class="o">{</span>
    <span class="kd">static</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">loadLibrary</span><span class="o">(</span><span class="s">&quot;hello_world_jni&quot;</span><span class="o">);</span> <span class="c1">//this loads the library when the class is loaded</span>
    <span class="o">}</span>
</code></pre></div>
<p>This is a static initializer, it loads the JNI module only once when the class is first loaded, not every time an instance is made. Then, change the <code>helloWorld()</code> function as shown and add the new <code>helloWorldJNI()</code> declaration below it.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="nd">@ReactMethod</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">helloWorld</span><span class="o">(</span><span class="n">Promise</span> <span class="n">promise</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">String</span> <span class="n">hello</span> <span class="o">=</span> <span class="n">helloWorldJNI</span><span class="o">();</span>
        <span class="n">promise</span><span class="o">.</span><span class="na">resolve</span><span class="o">(</span><span class="n">hello</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">promise</span><span class="o">.</span><span class="na">reject</span><span class="o">(</span><span class="s">&quot;ERR&quot;</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="kd">public</span> <span class="kd">native</span> <span class="n">String</span> <span class="nf">helloWorldJNI</span><span class="o">();</span>
</code></pre></div>
<p>We&#39;ve now changed the <code>helloWorld()</code> function to get a string by calling <code>helloWorldJNI()</code>. This references the declaration below it, <code>public native String helloWorldJNI()</code>. The <code>native</code> keyword indicates to Java that this is a JNI function, and it will find the function in C, not Java. Note that if you&#39;re using Android Studio, it will warn you if it can&#39;t find an appropriately named function in C (<code>Java_com_thebhwgroup_demo_HelloWorldModule_helloWorldJNI</code> in our case) and show you what the name of the function it&#39;s looking for is.</p>

<p>At this point, you should be able to recompile and run your app, and it will again log &quot;Hello World!&quot; into the Android logcat. You shouldn&#39;t really notice any difference as it&#39;s still just getting a string and logging it in React Native, but this time it&#39;s getting it from C, not Java.</p>

<h2>Real World JNI</h2>

<p>Now that you&#39;ve got a very basic, working example of JNI, it&#39;s time to write some practical code. Chances are your C function is going to take more than 0 parameters and return more than just a string.<br>
The C library we were writing code for had quite a few structs we would have to represent in JavaScript. The most complicated of which had both other structs and an array of structs as some of its members. The solution we came up with does require a decent chunk of boilerplate and somewhat repetitive code at first, but it makes things easier later on.</p>

<h3>Java to C and Back Again</h3>

<p>We initially wrote our code by breaking up JavaScript objects into their respective members in Java and passing every member in as its own parameter to JNI functions. Not only is this incredibly tedious and messy, it straight up doesn&#39;t work for arrays. We then instead chose to make a Java class that was a counterpart to the C struct that we were working with. So let&#39;s say a C library has the following structs.</p>
<div class="highlight"><pre><code class="language-c" data-lang="c"><span class="c1">//defs.h</span>
<span class="cp">#ifndef DEFS_H</span>
<span class="cp">#define DEFS_H</span>

<span class="k">typedef</span> <span class="k">struct</span>
<span class="p">{</span>
    <span class="kt">double</span> <span class="n">x</span><span class="p">;</span>
    <span class="kt">double</span> <span class="n">y</span><span class="p">;</span>
<span class="p">}</span> <span class="n">MyVector</span><span class="p">,</span> <span class="o">*</span><span class="n">pMyVector</span><span class="p">;</span>

<span class="k">typedef</span> <span class="k">struct</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">vector_count</span><span class="p">;</span>
    <span class="n">MyVector</span><span class="o">*</span> <span class="n">vectors</span><span class="p">;</span>
    <span class="n">MyVector</span> <span class="n">position</span><span class="p">;</span>
<span class="p">}</span> <span class="n">MyStruct</span><span class="p">,</span> <span class="o">*</span><span class="n">pMyStruct</span><span class="p">;</span>

<span class="cp">#endif</span>
</code></pre></div>
<p>This struct is much simpler than the JBM library structs we were using, but covers the unique cases we came across.<br>
Given this, you now want to make analogous classes in Java. Add the following files to the same directory as <code>HelloWorldModule.java</code> and the other class files.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="c1">//MyVector.java</span>
<span class="kn">package</span> <span class="n">com</span><span class="o">.</span><span class="na">thebhwgroup</span><span class="o">.</span><span class="na">demo</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyVector</span> <span class="o">{</span>
    <span class="kt">double</span> <span class="n">x</span><span class="o">;</span>
    <span class="kt">double</span> <span class="n">y</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">MyVector</span><span class="o">()</span> <span class="o">{}</span>

    <span class="kd">public</span> <span class="nf">MyVector</span><span class="o">(</span><span class="kt">double</span> <span class="n">x</span><span class="o">,</span> <span class="kt">double</span> <span class="n">y</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">x</span> <span class="o">=</span> <span class="n">x</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">y</span> <span class="o">=</span> <span class="n">y</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre><code class="language-java" data-lang="java"><span class="c1">//MyStruct.java</span>
<span class="kn">package</span> <span class="n">com</span><span class="o">.</span><span class="na">thebhwgroup</span><span class="o">.</span><span class="na">demo</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyStruct</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">vector_count</span><span class="o">;</span>
    <span class="n">MyVector</span><span class="o">[]</span> <span class="n">vectors</span><span class="o">;</span>
    <span class="n">MyVector</span> <span class="n">pos</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">MyStruct</span><span class="o">()</span> <span class="o">{}</span>

    <span class="kd">public</span> <span class="nf">MyStruct</span><span class="o">(</span><span class="kt">int</span> <span class="n">vector_count</span><span class="o">,</span> <span class="n">MyVector</span><span class="o">[]</span> <span class="n">vectors</span><span class="o">,</span> <span class="n">MyVector</span> <span class="n">pos</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">vector_count</span> <span class="o">=</span> <span class="n">vector_count</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">vectors</span> <span class="o">=</span> <span class="n">vectors</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">pos</span> <span class="o">=</span> <span class="n">pos</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<p>These Java classes can be passed as is to the native functions and will be cast to <code>jobject</code> in C. For an example, let&#39;s define another native function in <code>HelloWorldModule.java</code>. At the bottom of the class definition, add the line <code>public native MyStruct helloStructJNI(MyStruct struct, double d);</code>. We&#39;re passing both a Java class and primitive to give examples of how you handle both complex and primitive types in JNI.</p>

<p>The equivalent C function will be defined as <code>jobject Java_com_thebhwgroup_demo_HelloWorldModule_helloStructJNI(JNIEnv* env, jobject thiz, jobject jstruct, jdouble jd)</code>. The first 2 parameters are the <code>JNIEnv</code> and <code>jobject</code> that are part of every JNI invoked function, the third parameter is our <code>MyStruct</code> (now a <code>jobject</code>), and the fourth is the <code>double</code> (now a <code>jdouble</code>, which as mentioned earlier is still just a <code>double</code>).</p>

<p>Since the <code>jdouble</code> is just a typedef, it can be used as is and passed to any C functions that need it. However, a C <code>MyStruct</code> needs to be made out of the <code>jobject</code> before it can be used with any C function expecting a <code>MyStruct</code>. This is done via a couple JNI functions, which we&#39;ve set up and added to <code>hello_world.c</code>. Since there are a lot of steps in this, we&#39;ve gone and finished the hello_world.c file, which you can view on GitHub.</p>

<p><a href="https://github.com/rdixonbhw/ReactNative-JNI-Blog/blob/master/android/app/src/main/jni/hello_world.c">hello_world.c on GitHub</a></p>

<p>There&#39;s a lot of new stuff going on here, so let&#39;s go through and explain the details of the less obvious parts. First we import Android logging functions, the JNI header, stdlib for malloc, and our <code>defs.h</code> file defining <code>MyVector</code> and <code>MyStruct</code>. Next we set up some helpful #defines for Android logging. Calling <code>LOGD()</code> later in code will have the same behavior as calling <code>Log.d()</code> in Java and the log with <code>jni_hello_world</code></p>

<p>Lines 13 to 26 declare a couple JNI types. These variables are used by JNI to associate a <code>jobject</code> with a Java class and work with the data it holds. For each struct there is a <code>jclass</code>, used to refer to the Java class, a <code>jmethodID</code> which refers to the constructor method of the class, and a couple <code>jfieldID</code>s which are used to refer to the fields of the Java class. Finally, there is a <code>jclass</code> which will be set up to refer to a generic Java exception in the event we need to throw one.</p>

<h4>JNI_OnLoad</h4>

<p>All of these variables are setup in the <code>JNI_OnLoad()</code> function. <code>JNI_OnLoad</code> is called when the library is loaded (by our <code>System.loadLibrary()</code> call made in Java), and is expected to return the version needed by the library. Android docs says to use <code>JNI_VERSION_1_6</code>. We&#39;ve commented the setup calls for <code>MyStruct</code> in the loading function as they&#39;re more complicated than the setup calls for <code>MyVector</code>, and if you understand these you&#39;ll understand the easier ones. The first one sets <code>jclass MY_STRUCT</code>. It makes a call to <code>FindClass()</code> passing it <code>env</code> (all JNI functions need this), and the fully qualified name of <code>MyStruct</code> in Java. The fully qualified name of a class is the package name (<code>com.thebhwgroup.demo</code> in our case) followed by the class name (<code>MyStruct</code>), with slashes replacing periods. So while we&#39;ve named our Java class MyStruct to make its C pairing clear, you could name it whatever you want as long as you refer to it correctly. Finally the return from <code>FindClass</code> is wrapped in a call to <code>NewGlobalRef()</code> (also passing <code>env</code> again). This is done as the reference returned from <code>FindClass()</code> is only local and will only persist through this function call. We however will need to use <code>MY_VECTOR</code> continuously in other function calls, so we hold onto it with a global reference.</p>

<p>Next we get the <code>jmethodID</code> of the <code>MyStruct(int vector_count, MyVector[] vectors, MyVector position)</code> constructor. In C, both <code>jmethodID</code> and <code>jfieldID</code> are pointers to opaque structures. In the call to <code>GetMethodID()</code>, we pass the following parameters</p>

<ul>
<li><code>env</code> as is required to all JNI functions</li>
<li><code>MY_STRUCT</code> which now refers to the <code>MyStruct</code> Java class and is sort of telling <code>GetMethodID()</code> where to &quot;look&quot;</li>
<li>the function name, which since it&#39;s a constructor is always <code>&quot;&lt;init&gt;&quot;</code></li>
<li>the type signature of the constructor method, <code>&quot;(I[Lcom/thebhwgroup/demo/MyVector;Lcom/thebhwgroup/demo/MyVector;)V&quot;</code></li>
</ul>

<p>The type signature is probably the oddest part of this call. There are two ways to get this, write it yourself, or use <code>javap</code> to get it for you, the latter of which is less error prone.</p>

<p><code>javap</code> requires that you have built the APK at least once with the Java class you need to get the signature of. If you&#39;ve done so, you should be able to run <code>javap -classpath android/app/build/intermediates/classes/debug -s com.thebhwgroup.demo.MyStruct</code> from your React Native project directory. If you&#39;re running from somewhere else, replace the <code>-classpath</code> argument with the equivalent relative directory, and the <code>-s</code> argument with the name of your package and class in the event they are different. Assuming this works, you should see some output in the console. You&#39;re most interested in the following lines.</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">public com.thebhwgroup.demo.MyStruct(int, com.thebhwgroup.demo.MyVector[], com.thebhwgroup.demo.MyVector);
    descriptor: (I[Lcom/thebhwgroup/demo/MyVector;Lcom/thebhwgroup/demo/MyVector;)V
</code></pre></div>
<p>Specifically the <code>descriptor:</code> line. Everything after the colon and leading space is the JNI method signature for the constructor method you want. In the event you can&#39;t get this to work, or are more interested in the signature, we&#39;ll also go over what exactly it means.</p>

<p>The <code>MyStruct</code> constructor takes an <code>int</code>, an array of <code>MyVector</code>, and a lone <code>MyVector</code> as its three parameters and returns <code>void</code>. The return value is the last part of the signature and is the <code>V</code> at the end of the string. The part of the string in parentheses is the signature of the parameters. The signature of a primitive type is easy, just a single letter, and in the case of an <code>int</code> it&#39;s the letter <code>I</code>. The signature for an array of a Java class is a little more. It&#39;s a <code>[</code> indicating an array and then the letter <code>L</code> followed by the fully qualified name of the Java class terminated with a semicolon. So in all, <code>[Lcom/thebhwgroup/demo/MyVector;</code> is the signature of an array of <code>MyVector</code> in the package <code>com.thebhwgroup.demo</code>. The signature of the final method parameter is the same as the previous one without the <code>[</code> as it&#39;s not an array, <code>Lcom/thebhwgroup/demo/MyVector;</code>. And there you have it, the signature of a method with its parameters and return type. This is explained more in the Type Signatures section of the <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html">JNI Types</a> spec.</p>

<p>Now that we have the <code>jmethodID</code>, we&#39;ll get the <code>jfieldID</code>s for the class fields. We first get the simplest field in <code>MyStruct</code>, <code>int vector_count</code>. <code>GetFieldID()</code> takes parameters similar to <code>GetMethodID()</code>, taking a field name instead of a method name and a field type signature instead of a method type signature. The field name here is <code>&quot;vector_count&quot;</code> and the type signature is just <code>&quot;I&quot;</code> since it&#39;s an int. Next we get the <code>jfieldID</code>s for <code>vectors</code> and <code>position</code>. You should recognize these type signatures as they were also used in getting the constructor method ID.</p>

<p>Finally, we get the class for a Java exception, which can later be used to throw an exception.</p>

<p>Just so you&#39;re aware, you don&#39;t have to do it like this. You could instead make calls to <code>GetMethodID()</code> and <code>GetFieldID()</code> anytime you need the methods and fields. If you&#39;re only using them once, it&#39;s probably better to do just that. When we were writing BallisticsARC we knew we were going to have to use these a couple times, so we went ahead and saved it all to variables for two reasons, cleaner code and because these lookups are <em>slow</em>. <code>FindClass()</code> for example, &quot;searches the directories and zip files specified by the CLASSPATH environment variable for the class with the specified name.&quot; IBM benchmarked <code>GetFieldID()</code> and found that in six calls to <code>GetIntField()</code>, using a cached field ID instead of calling <code>GetFieldID()</code> every time was 24 times faster. So in this space-time tradeoff, a little more space saves a lot more time.</p>

<p>Also, be aware that every one of these JNI calls could be silently creating an exception. In general you should watch for these with <code>if ((*env)-&gt;ExceptionCheck(env))</code>, we however have chosen not to. The code we needed to run in C was so integral to our app, that if it failed to initialize our app might as well crash as there is no saving it at that point. However, if an ungraceful crash is not your intention, you should be handling exceptions.</p>

<h4>Helper Functions</h4>

<p>Now that all the needed JNI variables are initializaed it&#39;s time to put them to use. For each C struct there is a <code>make_native_...</code> function which will take a <code>jobject</code> and return a C struct that can then be passed to third party library functions. Just as before we&#39;re only going to walk through the more complicated of the two under the assumption that if you understand it you&#39;ll understand the simpler one. <code>make_native_my_struct()</code> takes a <code>JNIEnv</code> and a <code>jobject</code> that represents a Java <code>MyStruct</code>. First we declare a C <code>MyStruct</code> which will be set with all the data from the Java one. Next we set the value for <code>vector_count</code> which is pretty easy as it&#39;s just an int. We make a call to <code>GetIntField()</code> and pass it the following</p>

<ul>
<li><code>env</code>, the JNIEnv pointer as always</li>
<li><code>jstruct</code>, the jobject it is getting the int from</li>
<li><code>MY_STRUCT_VECTOR_COUNT</code>, the jfieldID of the int field, which was set earlier in <code>JNI_OnLoad</code></li>
</ul>

<p>There are similar functions for other primitive types. If you check <code>make_native_my_vector</code>, you&#39;ll notice it&#39;s simply setting the <code>x</code> and <code>y</code> fields with two calls to <code>GetDoubleField()</code> with the corresponding <code>jfieldID</code>.</p>

<p>Next we set <code>position</code>, which is a little more complicated since it&#39;s a struct. However, we&#39;ve made this step easier by using <code>make_native_my_vector()</code>, the process of which should make sense if you understood the use of <code>GetIntField()</code>. We use <code>GetObjectField()</code> to get another <code>jobject</code> from our first <code>jobject jstruct</code>. The call to this is just like <code>GetIntField()</code> except for its return. We pass it</p>

<ul>
<li><code>env</code></li>
<li><code>jstruct</code>, the <code>jobject</code> we&#39;re getting the field from</li>
<li><code>MY_STRUCT_POSITION</code>, the <code>jfieldID</code> for <code>position</code> that was set in <code>JNI_OnLoad</code></li>
</ul>

<p>We then immediately pass the resulting <code>jobject</code> to <code>make_native_my_vector()</code> (along with <code>env</code>), to get a <code>MyVector</code> that can be assigned to <code>position</code>.</p>

<p>The final field, <code>vectors</code>, is the most complicated one as it&#39;s an array of Java classes. First the array in the C struct needs to be initialized with <code>malloc()</code> using <code>my_struct.vector_count</code> as the size. Next we get the <code>jobject</code> field from <code>jstruct</code>, only this time we assign it to a <code>jobjectArray</code>. We then iterate through the array, setting each element of <code>vectors</code> by getting a <code>jobject</code> from the array and passing it to <code>make_native_my_vector()</code>. <code>GetObjectArrayElement()</code> works similar to <code>GetObjectField()</code>, but instead of taking a field ID, it takes an index in the array. Remember when doing this to call <code>DeleteLocalRef()</code> after you&#39;re done with the <code>jobject</code>. Each call to <code>GetObjectArrayElement()</code> makes a local reference and the JNI implementation only guarantees 16 of those per function call. You could find yourself in some trouble if you never delete those references.</p>

<p>With these functions a <code>jobject</code> passed in from JNI can now be turned into a corresponding C struct that can then be used like any other struct. But more functions are still needed to make a <code>jobject</code> out of a C struct so that it can be returned to JNI.</p>

<p>Making a <code>jobject</code> from the <code>struct MyVector</code> is actually a single line since it only consists of primitive types. However we still chose to make a function (<code>make_jni_my_vector</code>) for it for consistency and because it&#39;s cleaner and easier to remember than a <code>NewObject()</code> call. This also becomes more useful the more fields a struct has. Making a <code>jobject</code> from a <code>MyStruct</code> (done in <code>make_jni_my_struct</code>) is made more complicated by the array of structs. First a new <code>jobjectArray</code> is allocated; we pass <code>NewObjectArray</code> the following</p>

<ul>
<li><code>env</code></li>
<li><code>vector_count</code>, the size of the array</li>
<li><code>MY_VECTOR</code>, the object type of the array</li>
<li><code>NULL</code>, an element used for initialization</li>
</ul>

<p>Since <code>MyVector</code>s are immediately going to be copied into the array, it&#39;s initialized with <code>NULL</code> for now. Next the array elements are copied into the <code>jobjectArray</code>. We iterate through every <code>MyVector</code> in <code>vectors</code>, and for each one call <code>SetObjectArrayElement()</code>, passing the following</p>

<ul>
<li><code>env</code></li>
<li><code>ja_vectors</code>, the destination <code>jobjectArray</code> we&#39;re copying into</li>
<li><code>i</code>, the index in the array that we&#39;re setting</li>
<li>the data to be set at the index, which we get by making a call to <code>make_jni_my_vector()</code>, which returns a <code>jobject</code> of the vector</li>
</ul>

<p>We&#39;ve made an assumption in our code that if you&#39;re making a <code>jobject</code> out of a struct you&#39;re done with the struct, so at that point we call <code>free()</code> on the array previously allocated with <code>malloc()</code> to return that memory. Last, we create a <code>jobject</code> of <code>MyStrcut</code> with a call to <code>NewObject()</code> and return it. To <code>NewObject()</code> we pass</p>

<ul>
<li><code>env</code></li>
<li><code>MY_STRUCT</code> the jobject &quot;type&quot; were making</li>
<li><code>MY_STRUCT_CONS</code> a reference to the <em>Java</em> method used to construct the class</li>
<li><code>my_struct.vector_count</code>, the first parameter to the <code>MY_STRUCT_CONS</code> constructor, which is passed as is since JNI can handle the primitive conversion</li>
<li><code>ja_vectors</code> the <code>jobjectArray</code> which will get converted to a <code>[]MyVector</code> by JNI and passed as the second parameter to the constructor</li>
<li>the third paramater to the constructor, a <code>jobject</code> of <code>position</code> which is made with <code>my_struct.position</code> passed to <code>make_jni_my_vector</code></li>
</ul>

<p>And that&#39;s it, all needed helper/utility functions are now finished and ready for use. If you look at <code>Java_com_thebhwgroup_demo_HelloWorldModule_helloWorldJNI()</code> (the C function for the <code>native helloWorldJNI()</code> method in <code>HelloWorldModule</code>), you&#39;ll see why we set all this up. Instead of having all those JNI calls in our function, there&#39;s just the single line <code>MyStruct my_struct = make_native_my_struct(env, jstruct);</code>. This struct can be used in a couple calls to LOGD to log its contents to the Android logcat. We&#39;ve commented out what a call to create an exception would look like (as that&#39;s not intended right now), but if one of these calls could fail, you would want to check it and call <code>ThrowNew()</code> (passing it the <code>JAVA_EXCEPTION</code> jclass) to allow Java to deal with the failure. Our function finishes with a call to <code>make_jni_my_struct</code> to return the <code>MyStruct</code> back to Java as a <code>jobject</code>.</p>

<p>Clearly this function doesn&#39;t actually do anything yet. But using the convenience functions for making structs and jobjects as needed, it&#39;s much easier to prepare data for manipulation in C. When writing BallisticsARC, we went through the JBM library and found all entry points we would be calling. We then wrote wrappers to move data to and from Java and C for all of the needed JBM functions. This made the <code>make_jni...</code> and <code>make_native...</code> functions very useful to us as we had multiple Java classes with 10+ fields, and 5-6 C function that we&#39;d need to call with them. With this setup we were able to easily make JBM C structs from Java classes and pass them as needed to JBM functions. By doing so we didn&#39;t have to look at or change any JBM code to make it able to interact with all the JNI types we had.</p>

<p>It&#39;s time to to actually test our code. Back in Java, add the following snippet to the try block in the <code>helloWorld()</code> function that gets called by React Native.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">MyVector</span><span class="o">[]</span> <span class="n">vectors</span> <span class="o">=</span> <span class="o">{</span><span class="k">new</span> <span class="nf">MyVector</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">1</span><span class="o">),</span> <span class="k">new</span> <span class="nf">MyVector</span><span class="o">(</span><span class="mi">2</span><span class="o">,</span> <span class="mi">2</span><span class="o">),</span> <span class="k">new</span> <span class="nf">MyVector</span><span class="o">(</span><span class="mi">3</span><span class="o">,</span> <span class="mi">3</span><span class="o">)};</span>
<span class="n">MyStruct</span> <span class="n">myStruct</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">MyStruct</span><span class="o">(</span>
        <span class="n">vectors</span><span class="o">.</span><span class="na">length</span><span class="o">,</span>
        <span class="n">vectors</span><span class="o">,</span>
        <span class="k">new</span> <span class="nf">MyVector</span><span class="o">(</span><span class="mi">10</span><span class="o">,</span> <span class="mi">15</span><span class="o">));</span>
<span class="n">MyStruct</span> <span class="n">newStruct</span> <span class="o">=</span> <span class="n">helloStructJNI</span><span class="o">(</span><span class="n">myStruct</span><span class="o">,</span> <span class="mi">47</span><span class="o">);</span>
</code></pre></div>
<p>(There&#39;s no reason to any of the chosen numbers) Rebuild, run your app, and check the Android logs (<code>adb logcat -s jni_hello_world</code> to filter only the JNI logs, assuming you have <code>#define LOG_TAG &quot;jni_hello_world&quot;</code> in hello_world.c). If everything is going well you should see the following in the logs.</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">jni_hello_world: double 47.000000
jni_hello_world: struct vector_count 3
jni_hello_world: struct vectors
jni_hello_world: vector 0 (1.000000, 1.000000)
jni_hello_world: vector 1 (2.000000, 2.000000)
jni_hello_world: vector 2 (3.000000, 3.000000)
jni_hello_world: struct pos (10.000000, 15.000000)
</code></pre></div>
<p>If not, either you aren&#39;t calling <code>helloWorldJNI()</code> correctly or your app has probably just crashed. If it has crashed, go through the Android logs (you&#39;ll need to run <code>adb logcat</code> again if you ran it with the <code>-s</code> flag previously) and look for <code>JNI DETECTED ERROR IN APPLICATION</code> (it&#39;ll likely be right before an enormous stack trace). Chances are one of the many JNI calls you&#39;re making failed, made an exception, and you made another call afterwards without checking for an exception. Our most common error was a class, method, or field not being found with the fully qualified name and type signature we had given. You&#39;ll probably see something along the lines of <code>JNI DETECTED ERROR IN APPLICATION: JNI &lt;method&gt; called with pending exception &lt;exception&gt;</code>. Look at what the exception is, and hopefully it&#39;s a clear enough description to fix. If it is JNI being unable to find a method, class, or field as you&#39;ve described it, double check your fully qualified name and type signature, and try comparing it to <code>javap</code> output as was mentioned before. A note for when you rebuild, we occasionally ran into an issue where it looked like Android Studio didn&#39;t notice C code changes, meaning we would have to clean the project, uninstall the APK, and then rebuild and run. This is generally accompanied with <code>No local changes, not deploying APK</code> in the Android Studio logs.</p>

<h3>JavaScript to Java and Back Again</h3>

<p>Our React Native code is now calling C code, but no data is being passed to and from it. Since we have Java&lt;-&gt;C data conversion set up for our types, we just need to make a JavaScript&lt;-&gt;Java conversion. This process is easier than Java to C as React Native handles the JavaScript side of conversion. Conversion of primitive types is straight forward. For example, a number in JS can be an int, double, or float in Java, and vice versa. Java classes and arrays are a little more complicated. React Native added two Java classes, <a href="https://reactnative.dev/docs/new-architecture-appendix#object">ReadableMap</a> and <a href="https://reactnative.dev/docs/new-architecture-appendix#object">ReadableArray</a>, both of which also have writable versions. The ReadableMap is just that, a map. It has methods to check for the existence of a key, along with getting a value from a key. The ReadableArray has the same thing, but instead of getting values from keys, they&#39;re gotten by indices. Setting up the conversion to and from JavaScript in Java requires the addition of two new methods to MyVector and three new methods to MyStruct, the complete versions of which are linked below.</p>

<ul>
<li><a href="https://github.com/rdixonbhw/ReactNative-JNI-Blog/blob/master/android/app/src/main/java/com/thebhwgroup/demo/MyVector.java">MyVector.java on GitHub</a></li>
<li><a href="https://github.com/rdixonbhw/ReactNative-JNI-Blog/blob/master/android/app/src/main/java/com/thebhwgroup/demo/MyStruct.java">MyStruct.java on GitHub</a></li>
</ul>

<p>Just like with the JNI section, we&#39;ll explain the MyStruct conversion process and assume the MyVector conversion is understandable from that. The first new addition to MyStruct.java is the constructor <code>MyStruct(ReadableMap map)</code>. Since a ReadableMap is passed to Java from React Native, it needs to be converted a MyStruct so that it can freely be used in Java. This constructor simply calls the original constructor that takes an <code>int</code>, <code>MyVector[]</code>, and a <code>MyVector</code>. Getting the int from the map is done via a call to <code>getInt</code> with the key for <code>vector_count</code>. Note that these keys map to the object&#39;s properties in JavaScript, so if the properties of your JavaScript object are not the same as your Java class variable names you&#39;ll need to put whatever the property is in JavaScript for the key. Next we get a ReadableArray from the map with <code>getArray()</code> and pass this array to another helper function we&#39;ve made, which will be explained shortly. Last we get a ReadableMap for <code>position</code> from <code>map</code> and pass it to the MyVector constructor that takes a ReadableMap, the function of which should now be apparent based on the function of this <code>MyStruct</code> constructor.</p>

<p>Onto <code>MyVectorArrayFromReadableArray()</code> at the bottom. It starts by allocating a new MyVector[] based on the size of the ReadableArray. It then iterates through the ReadableArray and passes each ReadableMap to the associated MyVector constructor. Pretty simple.</p>

<p>The third function is used to get a WritableMap from MyStruct, that way React Native can convert it to a JavaScript object. We start by creating a new WritableMap. We then set the key <code>&quot;vector_count&quot;</code> to be the int <code>vector_count</code>. Next we create a new WritableArray for <code>vectors</code>. We iterate through <code>vectors</code>, convert each one to its own WritableMap, and push the map to the WritableArray. Last we convert <code>position</code> to a WritableMap and set it for the key <code>&quot;position&quot;</code> in <code>map</code>. And with that we have a WritableMap that&#39;s ready to be given to React Native.</p>

<p>To test this, change the helloWorld function in HelloWorldModule.java to accept a new parameter instead of using its own <code>MyStruct</code>.</p>

<h4>HelloWorldModule.java</h4>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="nd">@ReactMethod</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">helloWorld</span><span class="o">(</span><span class="n">ReadableMap</span> <span class="n">structMap</span><span class="o">,</span> <span class="kt">double</span> <span class="n">num</span><span class="o">,</span> <span class="n">Promise</span> <span class="n">promise</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">MyStruct</span> <span class="n">myStruct</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">MyStruct</span><span class="o">(</span><span class="n">structMap</span><span class="o">);</span>
        <span class="n">MyStruct</span> <span class="n">newStruct</span> <span class="o">=</span> <span class="n">helloStructJNI</span><span class="o">(</span><span class="n">myStruct</span><span class="o">,</span> <span class="n">num</span><span class="o">);</span>
        <span class="n">promise</span><span class="o">.</span><span class="na">resolve</span><span class="o">(</span><span class="n">newStruct</span><span class="o">.</span><span class="na">toWritableMap</span><span class="o">());</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">promise</span><span class="o">.</span><span class="na">reject</span><span class="o">(</span><span class="s">&quot;ERR&quot;</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<p>This function now expects an object and a number from its invocation in JavaScript. Note that the <code>Promise</code> used to return data to JavaScript is always the last parameter to the Java function. The new MyStruct returned from <code>helloStructJNI()</code> is converted to a <code>WritableMap</code> and used to resolve the promise, which returns the data to JavaScript. To test this, the call to <code>helloWorld()</code> in React Native has to be changed.</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">let</span> <span class="nx">struct</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nx">vector_count</span><span class="o">:</span> <span class="mi">3</span><span class="p">,</span>
    <span class="nx">vectors</span><span class="o">:</span> <span class="p">[</span>
        <span class="p">{</span>
            <span class="nx">x</span><span class="o">:</span> <span class="mi">10</span><span class="p">,</span>
            <span class="nx">y</span><span class="o">:</span> <span class="mi">10</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="p">{</span>
            <span class="nx">x</span><span class="o">:</span> <span class="mi">20</span><span class="p">,</span>
            <span class="nx">y</span><span class="o">:</span> <span class="mi">20</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="p">{</span>
            <span class="nx">x</span><span class="o">:</span> <span class="mi">30</span><span class="p">,</span>
            <span class="nx">y</span><span class="o">:</span> <span class="mi">30</span><span class="p">,</span>
        <span class="p">},</span>
    <span class="p">],</span>
    <span class="nx">position</span><span class="o">:</span> <span class="p">{</span>
        <span class="nx">x</span><span class="o">:</span> <span class="mi">12</span><span class="p">,</span>
        <span class="nx">y</span><span class="o">:</span> <span class="mi">34</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">};</span>
<span class="kd">let</span> <span class="nx">helloWorldStr</span> <span class="o">=</span> <span class="nx">await</span> <span class="nx">HelloWorld</span><span class="p">.</span><span class="nx">helloWorld</span><span class="p">(</span><span class="nx">struct</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.14</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">helloWorldStr</span><span class="p">);</span>
</code></pre></div>
<p>Just make an object, pass it and a number to <code>helloWorld.helloWorld()</code>, and log it. Now rebuild and run the app and check the logs (run <code>adb logcat -s ReactNativeJS,jni_hello_world</code> to filter only React Native <code>console.log()</code> and C <code>LOGD()</code> calls). If all goes well you should see the following in the logs.</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">jni_hello_world: double -3.140000
jni_hello_world: struct vector_count 3
jni_hello_world: struct vectors
jni_hello_world: vector 0 (10.000000, 10.000000)
jni_hello_world: vector 1 (20.000000, 20.000000)
jni_hello_world: vector 2 (30.000000, 30.000000)
jni_hello_world: struct pos (12.000000, 34.000000)
ReactNativeJS: { position: { y: 34, x: 12 },
ReactNativeJS:   vectors: [ { y: 10, x: 10 }, { y: 20, x: 20 }, { y: 30, x: 30 } ],
ReactNativeJS:   vector_count: 3 }
</code></pre></div>
<p>And there you have it! You&#39;re finally passing data from JavaScript down to C through Java and getting it back up in JavaScript. Go ahead and try actually manipulating it in C. Maybe double the vector values, or add another MyVector to the array (make sure to increment <code>vector_count</code>). You should see changes you make reflected in the returned JavaScript object.</p>

<h2>Wrap Up</h2>

<p>Hopefully this article has given you enough of a base to use C, JNI, Java, and React Native with your own libraries and needs. This was very new ground for us when we started as none of us had ever used JNI before. We&#39;re glad we were able to run third party C library code from our React Native app.  You&#39;ll probably run into situations different than the ones we&#39;ve set up, so remember the <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html">JNI Functions</a> and <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html">JNI Types</a> specs, along with React Native&#39;s <a href="https://facebook.github.io/react-native/docs/native-modules-android.html">Native Modules</a> guide and their <a href="https://reactnative.dev/blog/2018/04/09/build-com-app#bridge-modules">source code</a>. The Android docs also have a couple extra tips for writing JNI, along with sample projects of their own. We consulted all of these and more when writing BallisticsARC, and we hope we&#39;ve saved you some time and effort bringing it to one place.</p>

<p>What&#39;s next? You&#39;re probably writing your app in React Native so that you can also run it on iOS, but everything done here is Android specific. We&#39;ll soon be covering how to do the same thing and run C code from React Native on iOS. Lucky for you it&#39;s a lot easier. Objective C is a superset of C meaning you can take the <code>NSDictionary</code> React Native passes you and convert it directly to a C struct for your C libraries, skipping the JNI step.</p>

		]]></description>

    
        <category>react native</category>
    
        <category>Android</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>AngularJS - ngInfiniteScroll Example</title>
        <link>https://thebhwgroup.com/blog/nginfinitescroll</link>
		<author>Jason Gray</author>
		<pubDate>2016-08-08T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/nginfinitescroll</guid>
		<description><![CDATA[
		   #ngInfiniteScroll: Converting a home-grown “Show More” function to a more elegant AngularJS solution



I can think of numerous times in the past where I had some list of data on a webpage that would frequently require the ability for users to crawl deeper into the results in search of something.  In many of the more complex web and mobile applications that we build for clients, there is simply too much data to present in a confined space. We frequently come across the requirement for a data list control that allows for paging or scrolling.  This requirement has frequently materialized into a data grid or a sorted list with a custom function to go back to the server and request the next set(s) of records.  The goals are usually to gather the most essential subset of data, present that to the user on first load, and then allow the user to easily get to the rest of the data as needed.  I have recently started using the ngInfiniteScroll directive in our Angular projects for this type of feature, after seeing one of my teammates, Taylor Smith, implement it successfully.



In this article, I will review moving from a button to load more data to using the ngInfiniteScroll directive to load data as the user scrolls the list. Months ago, I had created a function to load an additional 30 days of patient data with a “Show More” button. As the application matured and we had greater amounts of older data that was only reviewed occassionally, I switched that to use this infinite scroll directive for a more elegant user experience.



## The Old (Custom):



In order to display 30 days of the patient’s data on the page load, there is an Angular service call to an api controller method.  The initial call passes in a patient’s id and parameters to get the most recent 30 days’ worth of data.



### The Angular service:



```javascript

function DocumentationService($resource, $q) {

    this.getByPatientIdForDays = function (id, daystart, dayend) {

        var deferred = $q.defer();

        var resource = $resource('api/Documentation/GetByPatientIdForDays', { Id: id, DayStart: daystart, DayEnd: dayend }, { 'query': { method: 'Get', isArray: true } });

        resource.query(function (response) {

            deferred.resolve(response);

        }, function (response) {

            deferred.reject(response);

        });

        return deferred.promise;

    };

}



module.service('Documentation', ['$resource', '$q', DocumentationService]);

```



### The MVC API Controller method



```C#

[Route("GetByPatientIdForDays")]

public IList<DocumentationDTO> GetByPatientIdForDays(int Id, int DayStart, int DayEnd)

{

    List<DocumentationDTO> docDTOs = new List<DocumentationDTO>();

    DateTime limitStart = DateTime.Now.AddDays(-DayStart);

    //If the start date was passed in as 0, find the most recent date for documentation

    if (DayStart == 0) { limitStart = DateTime.Now.AddDays(-(CalculateMostRecentDaysAgo(Id) + 30)); }

    DateTime limitEnd = DateTime.Now.AddDays(-DayEnd);



    IQueryable<Document> docs = _docRepository.AsQueryable().Where(x => x.PatientId == Id && x.CreatedDate > limitStart && x.CreatedDate <= limitEnd).OrderByDescending(x => x.CreatedDate);

    //The code then maps the query results to the DTO objects and returns that.

}

```





### The original load of the page sends in 0 for the date parameters and returns the array of results to a scope parameter named $scope.Documents



```javascript

return Documentation.getByPatientIdForDays(id, 0, 0);

```



In order for this feature to work, I needed to know a few things about the document data for the patient:



1. An integer value for the number of days from today to the earliest date of a patient’s documents.

    1. I added this as `$scope.mostDaysAgo`

    2. This value is set by an api call (GET) to a controller method called GetMostDaysAgo, which returns an integer.

2. An integer value for the number of days from today to the latest date of a patient document.

    1. I added this as `$scope.leastDaysAgo`

    2. This value is set by an api call (GET) to a controller method called GetLeastDaysAgo, which returns an integer.





```javascript

//Allow the user to move back until they reach the oldest records...  30 days at a time

//Get most recent data's date

$scope.getLeastDaysAgo = function () {

    $http({

        method: 'get',

        url: 'api/Documentation/GetLeastDaysAgoByPatientId?id=' + patient.Id

    }).success(function (data) {

        $scope.leastDaysAgo = data + 30; //start with 30 days back from first available data

    });

};

//Get oldest data's date

$scope.getMostDaysAgo = function () {

    $http({

        method: 'get',

        url: 'api/Documentation/GetMostDaysAgoByPatientId?id=' + patient.Id

    }).success(function (data) {

        $scope.mostDaysAgo = data;

    });

};

```



On the html page, we have Angular displaying the list of documents and the document properties that are important to the users.



```html

<div class="documentation-box">

    <div class="document-item" ng-repeat="doc in Documents">

    <h2>{{doc.Title}}</h2>

    ...



```



At the bottom of the results, we have a button to “Show More”, if applicable.  If the `$scope.mostDaysAgo` is less than 30 days ago, then this button and section will not be displayed at all.  The section and button will continue to be displayed until the user browses back in time to the oldest document data for this patient.



```html
<div class="document-item" ng-show="mostDaysAgo > 60">

    <h4>Currently showing results from {{ leastDaysAgoFmt }} through today.</h4>

    <h4>The oldest results for this patient are from {{ mostDaysAgoFmt }}.</h4>

    <button class="show-more btn" ng-click="showMore()" ng-show="mostDaysAgo > 30 && leastDaysAgo < mostDaysAgo">

        Show 30 Days More

    </button>

</div>
```



*The `leastDaysAgoFmt` and `mostDaysAgoFmt` scope variables are a formatted version of the start and end date.  They are used for display only.*



The Angular ng-click of the button (when enabled) makes a new call to a function that:



1.  Increments the days back in time you are viewing.

2.  Calls the controller method GetByPatientIdForDays(int Id, int DayStart, int DayEnd) to get a new set of data for the new parameters.

3.  Appends the resulting documents to what we are already displaying on the page so that the user can continue to scroll downward.  The document data already loaded remains on the page and the new data appears beneath it.



```javascript

$scope.showMore = function () {

    $scope.leastDaysAgo += 30;

    Documentation.getByPatientIdForDays(patient.Id, $scope.leastDaysAgo, $scope.leastDaysAgo - 30).then(function (response) {

        _.each(response, function (item) {

            $scope.Documents.push(item);

        });

    });

}

```



This process repeats until the user reaches the oldest documents for the patient and then the button will disappear.



**Currently showing results from 2/4/2016 through today. The oldest results for this patient are from 5/20/2015.**



<img src="/sites/default/images/blogs/2016-04-28-nginfinitescroll/showmorebtn.png" alt="Show More Button"/>



The user:

*Clicks button… (scrolls to bottom)…. Clicks button… (scrolls to bottom)…*



**Currently showing results from 5/20/2015 through today.**



##The New (ngInfiniteScroll):



There weren’t a ton of changes that needed to happen to implement an infinite scroll on the document data list.  We first needed to add ngInfiniteScroll to our application.  We used the instructions from the github site:



[GitHub - Infinite Scroll](https://github.com/sroze/ngInfiniteScroll)



We then added it to our Angular bundle and made it a new dependency in our main application module:



```javascript

var module = angular.module('{OUR_APPLICATION_NAME}', ['ngRoute', ..., 'infinite-scroll']);

```



Once the infinite scroll package was included in our application we made the necessary changes to the JavaScript functions on the document list page along with setting some new attributes on the corresponding elements in the html page:



```html

<div infinite-scroll='showMore()' infinite-scroll-disabled='loadingDocuments || mostDaysAgo <= 30 || leastDaysAgo >= mostDaysAgo' infinite-scroll-distance='1'>

```



* The infinite-scroll attribute defines the script function to call when triggered.

* The infinite-scroll-disabled attribute defines when the scrolling function is off.  In our case, scrolling will be disabled while the showMore() JavaScript function is in progress (waiting for results from the api call).  It will also be disabled when there are no more data points more than 30 days ago.

* The infinite-scroll-distance represents how close the bottom of the control (div) is to the bottom of the browser window and it defines when to trigger the infinite-scroll.  It is multiplier based on the height of the browser window.  The default value is 0, which would cause the event to trigger only when the bottom of the control came into view in the browser window.  If you set it at 2, for example, and your browser window was 1000 pixels in height, the event would fire when the bottom of the control was within 2000 pixels.  I played around with this value until it worked for our needs (set at 1).  Each document in our data takes up several hundred pixels in height, but if you are working with more row-oriented data that takes up little vertical space, then leave the attribute out altogether or set it to the default of 0.



I removed the “SHOW 30 DAYS MORE” button from the bottom, added a loading spinner, and kept the rest the same so that the user could still see the additional information about where they were in the history of the documents.



```html

<div class="document-item" ng-show="mostDaysAgo > 30">

    <h4>Currently showing results from {{ leastDaysAgoFmt }} through today. <span ng-show="loadingDocuments">Loading next 30 days...</span> <i ng-show="loadingDocuments" class="fa fa-spinner fa-pulse fa-4x loading-spinner"></i></h4>

    <h4>The oldest results for this patient are from {{ mostDaysAgoFmt }}.</h4>

</div>

```



I needed to add one additional `$scope` item (`loadingDocuments` to keep track of when the retrieval of more data was in process) and set it to false by default.  I then modified the `showMore` function to set that value to true while the script was waiting for the next set of documents and false afterwards.  This is also what triggers the loading spinner to show.



```javascript

$scope.showMore = function () {

    if ($scope.loadingDocuments) return;

    $scope.loadingDocuments = true;

    $scope.leastDaysAgo += 30;

    Documentation.getByPatientIdForDays(patient.Id, $scope.leastDaysAgo, $scope.leastDaysAgo - 30).then(function (response) {

        _.each(response, function (item) {

            $scope.Documents.push(item);

        });

        $scope.loadingDocuments = false;

    });

}

```



With the new changes, the page initially loads with the past 30 days of documentation like it did before.  If the user scrolls to the bottom of the list of documents, a new message saying “Loading next 30 days…”, the loading spinner graphic appear.  When the api call returns, the results show while the loading message and spinner hide.  The same will continue to happen when the user again scrolls to the bottom of the page until there are no longer any older results.  In our example, the end of the line would be 5/20/2015.



<img src="/sites/default/images/blogs/2016-04-28-nginfinitescroll/infinitescrollloading.png" alt="Currently showing - infinite scroll loading"/>



##Conclusion



Like most of you out there, I look for ways to improve my development work in order to make applications run more smoothly and to make them easier for the user.  This article explored a place where I had previously built a feature to allow users to explore older data, but users found this feature frustrating as the application matured and there was more archived data to browse through.  The ngInfiniteScroll directive provided an easier and more intuitive solution for users and I used this practical example to introduce you to this great tool.
		]]></description>

    
        <category>angularjs</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>Pragmatic Intro to React - March 2016 Austin ReactJS Meetup</title>
        <link>https://thebhwgroup.com/blog/intro-to-react</link>
		<author>Clayton Anderson</author>
		<pubDate>2016-03-14T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/intro-to-react</guid>
		<description><![CDATA[
		   {% include full-blog-image.html src="Clayton_March_React.PNG" alt="Clayton Anderson speaking at the March 2016 Austin React and React Native Meetup" %}

At BHW, we are big fans of [ReactJS](https://facebook.github.io/react/) and [React Native](https://facebook.github.io/react-native/). We have developed several web and mobile applications using these technologies and recently began organizing the [Austin React and React Native Meetup](http://www.meetup.com/Austin-ReactJS-Native-Meetup/). For the March 2016 Meetup, our speaker was Clayton Anderson. Clayton is our Technical Strategist and a Partner at The BHW Group. In this role he has been the lead developer on several React and React Native projects, he wrote our internal React app template, and trains all of our new web and mobile developers. His presentation was titled "A Pragmatic Intro to React." Below is a video of his presentation, his annotated slides, and code samples. This event was hosted at the newly opened [BazaarVoice](http://www.bazaarvoice.com/) office in North Austin.


##Presentation
<div class='embed-container'><iframe src='https://www.youtube.com/embed/3SUZwSKwtGA?start=294' frameborder='0' allowfullscreen></iframe></div>

##Slides
The slides for this presentation can be downloaded here: <a href="/pdfs/the_pragmatic_intro_to_react.pdf" target="_blank">Pragmatic Intro to React Slides</a>.

##Code
Here are the code samples from this presentation:
<script src="https://gist.github.com/pfrancis/4facd47fbde69a7c8311.js"></script>

##What's Next
If you enjoyed the presentation, please consider joining our [Meetup](http://www.meetup.com/Austin-ReactJS-Native-Meetup/)! If you have any feedback on this presentation or have topic requests for next time, please let us know. Thanks to everyone who came out to this Meetup! We enjoyed getting to meet other Austin React developers and are looking forward to the next meeting!
		]]></description>

    
        <category>react</category>
    
        <category>Meetup</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>Our Jekyll CMS migration from Drupal</title>
        <link>https://thebhwgroup.com/blog/jekyll-drupal-wordpress</link>
		<author>Brett Burnett</author>
		<pubDate>2015-11-16T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/jekyll-drupal-wordpress</guid>
		<description><![CDATA[
		   ##Why did we migrate from Drupal to Jekyll?
<div class="pull-quote pull-right">
	<div class="pull-quote-bar"></div>
	<div class="pull-quote-body">After fighting Drupal for two years we migrated to Jekyll</div>
	<div class="pull-quote-bar"></div>
</div>

Four years ago we migrated our website and blog to Wordpress.  I'll never forget the reaction when we announced the news to our team.  **Silence, quickly followed by irritation, resentment, and eventually a lot of cynical jokes.**  Two years after the move to Wordpress, we migrated to Drupal.  There were many reasons why Drupal was a better fit for us, and this time I was sure the team would be lining up to build content.  Unfortunately, the result was the same.  Both attempts succeeded from a technical standpoint, but adoption and engagement never got off the ground.  Our problem?  **BHW doesn't align with the audience that CMS solutions target.**  Our team is made up entirely of technical staff comfortable with HTML and Markdown.  Our staff feels hindered by traditional CMS solutions.  After two years on Drupal we migrated to [Jekyll](https://jekyllrb.com), a static site generator.  This time the reaction has been different.

{% include full-blog-image.html src="blogs/2015-11-16-jekyll-drupal-wordpress/cms.png" alt="Jekyll versus Drupal, Wordress, and Joomla for CMS" %}

To be clear, Wordpress and Drupal are mature CMS systems that, when designed, deployed, and cared for properly, offer easy authoring solutions for almost anyone.  **If your team isn't comfortable with HTML, text editors, and some basic source control, then a static site generator probably isn't for you.**  While static site generators aren't poised to take over from traditional CMS solutions, their rising popularity and numbers can't be overlooked.  Most businesses making a content authoring decision today will select a CMS, but what many don't consider is that you are committing to the platform and all it entails.  It's too easy to believe the selection of an open source CMS is a low cost, low risk decision.  Businesses incorrectly assume the "**free**" open source CMS should be easy to switch later, because after all it's "**free.**"  Carefully consider what you're signing up for:

 - **Security**
 - **Patching**
 - **Upgrades**
 - **Training**

Many of these efforts require good advice and guidance from consultants to be safe and effective.  The cost of a bad decision is higher than you would expect, simply because CMS migrations are complicated and your valuable content is stored in a content database and deeply nested directories, spread into many fragments.  **Putting your content back together can feel like an episode of a TV show with a team of people taping shredded documents together.**  A small mistake can mean that the SEO your team has worked so hard to build is lost due to duplicate content penalties, broken links, or missing metadata.

##Security
<div class="pull-quote pull-right">
	<div class="pull-quote-bar"></div>
	<div class="pull-quote-body">75% of PHP sites have known vulnerabilities</div>
	<div class="pull-quote-bar"></div>
</div>

Consider security for a moment.  The popular open-source CMS systems are based on PHP and use many plug-ins for even the most basic website.  There's been a lot of discussion lately about 75% of PHP sites having known vulnerabilities.  New sites are less likely to be exposed to these issues, which leaves you to focus concern on the CMS software itself.  While Drupal and Wordpress are carefully vetted for security flaws, vulnerabilities always slip through and require constant vigilance in the form of patching and updates.  Most CMS best practices recommend using as few plug-ins as possible to reduce the surface area for attacks.  **Plug-ins are usually written by much smaller teams, are patched less frequently, and in most CMS systems, are the principal entry point for attacks.**  Even if you invest the time to stay ahead of these issues, now you have to deal with human concerns like weak password complexity, shared passwords, etc.  An issue in any one of these areas opens your site to attack.

Compare this experience to a Jekyll generated static site.  Jekyll only runs on a workstation and produces static files.  Your server only runs a web server, a config file, and hosts your static files.  Instead of serving dynamic content from PHP-based CMS systems and their plug-ins, you serve static files through [Nginx](https://www.nginx.com) or [Apache](https://httpd.apache.org), two of the most **hardened and thoroughly tested web servers on the planet.**  Supporting Nginx or Apache couldn't be easier, with most linux distributions automatically updating these two packages for vulnerabilities.  The overhead and worry of running a PHP CMS is reduced to nearly zero.

<img src="/sites/default/images/blogs/2015-11-16-jekyll-drupal-wordpress/logo.jpg" alt="Jekyll deployed to Nginx or Apache"/>

**What about recovery?**  If your CMS has been running awhile, be prepared to face issues installing exactly the version of plug-ins and software you need, then patching up your vulnerability.  If your PHP CMS was hacked, you are probably facing a server reinstall and database restore, including a file system restore for your images and other assets.  Without a recent backup you will lose content and data.  Don't underestimate the time and complexity of a rebuild, and if you're concerned, ask your team or vendor to perform a restore test to make sure you're prepared in the event of an attack.  Be ready to watch their face fall as they consider the effort.  Even if you're lucky and have a snapshot backup to restore, you still have to bring it up and hope you can find the vulnerability and patch it before getting hacked again.  Recovery on Jekyll can be as simple as: 

 - **Provision a new VM**
 - **Install Nginx**
 - **Deploy your files**

Unlike a PHP CMS, there's no chance for content or data loss in Jekyll because your static files are deployed after being built on your local workstation.  With distributed and hosted source control, your site will be safe even if you lose access to your workstation.  Simply find another computer, pull down your source, install jekyll (it's a one-line command line install), and build your website.

##Performance
<div class="pull-quote-large pull-right">
	<img src="/sites/default/images/blogs/2015-11-16-jekyll-drupal-wordpress/stop-watch.jpg" alt="Jekyll performs better than Drupal, Joomla, and Wordpress"/>	
</div>

Performance is another advantage Jekyll holds over a PHP CMS.  A search of Google for Drupal or Wordpress performance will display many recommendations of plug-ins and proxy servers, two of the most popular being W3TotalCache and Varnish.  **Even after using these solutions, carefully tuning our configuration, and upgrading our server, we still couldn't reliably deliver our expected performance.**  A quick search will show the same performance challenges mentioned online.  Caching and proxy systems are used in an effort to overcome the poor performance exhibited by Drupal or Wordpress.  Both underlying CMS systems are very chatty, running many queries to render a single page.  Plug-ins make this worse by running their own queries too.  Viewing a typical page can generate hundreds of queries to the content database.  Caching is a great way to get around this problem, but has its own downsides too.  Caching strategies vary, but you often need a larger server with more RAM to cache your website.  Edits to single pages might be a quick cache update, but site-wide changes mean you have to completely rebuild the entire cache.  On our Drupal site, rebuilding the entire cache took almost 10 minutes, and the site was basically unusable while this occurred.  Proxy systems like varnish may even cache based on the HTTP User Agent, resulting in multiple copies of the website for different devices and browsers.  **We took the approach of pre-caching our site, but if we simply let the site render pages that missed the cache, we would see page loads over four seconds.**  Our move to Jekyll allowed us to retire all this infrastructure and simply use Nginx for serving static files, a task that it excels at.  It's so fast in fact that we were able to reduce the size of our VM server several times and save on hosting costs, all while proving better performance than before!

##Configuration Management
<div class="pull-quote pull-right">
	<div class="pull-quote-bar"></div>
	<div class="pull-quote-body">finding what to change and having confidence in its outcome can be a real challenge</div>
	<div class="pull-quote-bar"></div>
</div>

CMS systems bury their configuration in multiple settings pages.  Once you add modules to the mix with their own setup, you can easily have a situation where your configuration is stored in over ten different screens.  Couple that with the reality that your custom pages and blog content probably have their own settings and controls for their metadata and SEO information.  When you need to make a configuration change, finding what to change and having confidence in its outcome can be a real challenge.  Compare this to Jekyll's approach.  Configuration is stored in one of two places, the _config.yml file for system-wide concerns, or at the top of the page or post's individual file in the ["front matter"](http://jekyllrb.com/docs/frontmatter), a YAML section listing a simple collection of name-value pairs useful to the page.  Jekyll's approach is a welcome change to your average Drupal or Wordpress site.  It's very empowering to review your configuration information all in one place while having the ease of editing using text editor tools authoring, search and replace, etc.

###Content Versioning
In a traditional CMS system you may have content versioning (with a plug-in), but that feature seldom extends to versioning system configuration information and templates.  Usually you would create a database backup before configuration changes, naming the backup something appropriate to reference later if needed.  The backup is opaque.  **There's no way to know exactly what was changed, you simply have a before-and-after version of the system state.**  Jekyll's flat file approach is exactly the same, but fundamentally different in how it is applied.  Unlike database backups, flat files are easily compared, and differences are easy to understand using command line tools or GUI products like ["Beyond Compare"](http://www.scootersoftware.com).  Jekyll may accomplish the same end result of storing a before-and-after picture of the configuration state, but its done in a much more approachable fashion that provides amazing utility.  When you couple this approach with source control, you now have a visual record of the changes, a note about the reason, and an audit of who performed the change and when.   

<img src="/sites/default/images/blogs/2015-11-16-jekyll-drupal-wordpress/diff.png" alt="Jekyll allows easy calculation of differences to better understand what has changed" style="border: solid 1px #c9c9c9;"/>

**Jekyll's configuration management is so superior to a CMS that it's one of the main reasons we moved our website and blog from a database backed CMS.**  This one feature gives you easy fallback, branching support for testing new ideas, a contextual audit trail, comments, and more.  The power of this approach to change management extends even into the content itself, allowing pages and posts to be edited in the same powerful comparison context.  Don't underestimate the value of this key difference between these platforms.  At BHW, this one feature was the main reason we even researched flat file CMS systems to begin with.  Drupal and Wordpress have some plug-ins that promise visions of a similar approach, but many of these plug-ins have drawbacks and are frequently incompatible with other plug-ins you might select for your website.

##Cost
I started the article mentioning that many businesses underestimate the cost of a traditional open-source CMS.  Free software doesn't translate to having a "free" website.  Even if a business has a handle on the upfront cost, very few understand the upkeep cost.  Long-term cost breaks down into several categories:

 - **Hosting**
 - **Maintenance**
 - **Content Authoring**

Hosting cost can vary dramatically, but most analysis agrees that hosting Drupal or Wordpress can be expensive.  There's no question it's more expensive than hosting a static site generated by Jekyll.  Sites like github pages can now host Jekyll static sites for free.  Not every Jekyll site can make use of github pages though, which prevent the installation of certain plug-ins.  The difference in cost could be insignificant for smaller websites, but if your business has enough viewers and content, you will probably pay significantly more for hosting Drupal or Wordpress because you will be forced to pay for performance in the form of larger servers for caching.

<div class="pull-quote pull-right">
	<div class="pull-quote-bar"></div>
	<div class="pull-quote-body">Free software doesn't translate to having a "free" website.</div>
	<div class="pull-quote-bar"></div>
</div>

Maintenance is likely the cost most businesses underestimate.  **Ignoring maintenance is the central reason most websites gets hacked.**  Constant vigilance is required to monitor for vulnerabilities and install updates or patches.  Most of the time the update or patch can be installed easily; however, some updates require code or configuration changes.  Plug-ins might not port a patch to the version your website uses, forcing you to upgrade to a new version of the plug-in.  These code changes and forced upgrade events occur more than you would think, and they're always unexpected.  Usually you end up working in a staging environment to test the update before deploying to production.  In order to accurately test, it's important to mirror production as closely as possible, meaning synchronizing production content into staging.  This can be a time consuming effort on its own, but the truth is that few businesses do this.  **Most simply install to production and "hope for the best," then react if something goes wrong.**  Some likely consider it an educated gamble that saves the cost of running a second environment at the expense of some unexpected urgent website work if something goes wrong.  Once your open source CMS has been running awhile, you'll eventually have to make a major version upgrade, like going from Drupal 6 to 7 or 8.  These are extremely challenging and time-consuming events, and ignoring them puts you at risk since support for older versions of the base CMS solution fades quickly as new major versions are released.

##Authoring

<img src="/sites/default/images/blogs/2015-11-16-jekyll-drupal-wordpress/sublime.jpg" alt="Jekyll content authoring in sublime" />

Removing any barriers during content authoring was the biggest factor in exciting our team.  Few things can stop adoption faster than a poor experience in the authoring tools.  Once staff start contributing, the next challenge is how to help them make their content compelling and engaging.  Again, if the tools get in the way, our team is less likely to contribute.  In both cases we found that authoring from the familiar environment of a text editor like Sublime was far superior when compared to a browser-based CMS tool.  A third barrier is the infrastructure requirements for authoring, data connection, logins, VPN, etc.  We wanted to enable our team to author content wherever they were without jumping through hoops.  **A benefit we never expected from Jekyll is that it allows completely off-line authoring.**  Because Jekyll ships with an integrated web server for the authoring workstation, our staff can author even if they are offline without a data connection.  The final engagement hurdle to clear for our team was confidence.  CMS systems can present steep learning curves and the specter of a mistake in configuration can mean that your content is ineffective.  Jekyll's publishing and compositing system is so simple that it doesn't trigger the same anxiety that a complex CMS evokes.

##Flexibility
<div class="pull-quote pull-right">
	<div class="pull-quote-bar"></div>
	<div class="pull-quote-body">it's hard to imagine a more portable format for our content than Jekyll</div>
	<div class="pull-quote-bar"></div>
</div>

The last consideration is content flexibility.  How easy is it to move your content to another authoring solution?  We feel that Jekyll's static file approach is more "future-proof" than using a content database.  When we first performed our migration from Drupal to Jekyll, we tried to use a script to pull content.  Because we used plug-ins for metadata and images, the tool was unable to pull all of our content.  We had to write more scripts on our own, dig around in the database, and use Ruby code to piece things back together.  Even after the code efforts, we still had to do a manual scrub of many files.  Now that we're on Jekyll, if we ever decide to switch to a different CMS, it's difficult to imagine a more portable format for our content than Jekyll's static files.  Each file contains all the content and configuration settings needed for rendering on our website.  This is far more useful than piecing together content from a database.

##Conclusion
One thing we didn't discuss in this article is the initial website development.  At BHW we seldom develop websites from a template, preferring to build responsive websites best tailored to designer's visions using the appropriate tool for each job.  We routinely build integrations and websites on systems like Drupal and Wordpress for clients, and from our experience there's no question that Jekyll is easier, which translates into cheaper.  If your business can accommodate the higher technical bar that Jekyll imposes, it's undoubtedly a better value than a traditional CMS.  There are countless successful websites running on Wordpress and Drupal.  I'm happy to say that our website is no longer one of them.
		]]></description>

    
        <category>jekyll</category>
    
        <category>web development</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>Android Listview Examples and Guide</title>
        <link>https://thebhwgroup.com/blog/android-listview-guide</link>
		<author>Kevin Wade</author>
		<pubDate>2015-11-04T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/android-listview-guide</guid>
		<description><![CDATA[
		   Android ListViews have a bit of a learning curve, and they are used extensively in many apps including the recently released [Backspin Music Player](https://thebhwgroup.com/projects/lws-backspin).  I've put together a few tips and gotchas to keep in mind when working with them.  In this article I assume you understand how to set a ListView's adapter, but if you are brand new to using ListViews, learning that would be a good place to start.

{% include full-blog-image.html src="blogs/2015-11-4-android-listview-guide/backspin-1.jpg" alt="Example of an Android ListView from the Backspin App." %}

##View Recycling
One of the most important things to understand about ListViews is how they try to reuse their individual item views.  Inflating views for items that aren't on screen is wasteful. ListViews get around this by asking you to only inflate enough views for the visible items.  Then, when a view is scrolled off the end of the visible area, that view can be reused for the newly visible item at the other end of the list.  Adapters automatically take care of the recycling for you, so you just need to check if your list item's `getView` method is receiving a recycled view or not.  You only need to inflate a new view if the passed in convertView is null.

```java
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	if (convertView == null) {
		convertView = View.inflate(getActivity(), R.layout.item, parent);
	}
	...
	return convertView;
}
```

If you inflate a new view every time `getView` is called, instead of reusing the views, you are going to have a memory leak.  The ListView obviously has references to its item views, and it doesn't do anything to associate specific views with the data backing them.  This means that as you scroll up and down your list, you will keep inflating more and more views until either the list itself can be garbage collected or you run out of memory and crash.

{% include full-blog-image.html src="blogs/2015-11-4-android-listview-guide/backspin-2.jpg" alt="Example of an Android ListView from the Backspin App." %}

##The View Holder Pattern
If your list feels sluggish to scroll, it probably means that your adapter's `getView` is taking too long to run.  The View Holder pattern can help alleviate this.  The basic idea behind the View Holder pattern is to cache the results of `findViewById`, and it can be an easy way to improve your ListView's performance significantly. `findViewById` uses a simple recursive search of the view hierarchy to find the view you are looking for.  Generally speaking, the performance cost here isn't something to worry about, but the problems begin when your list item's layout starts getting complicated and users fling through your ListView quickly.  This can quickly result in hundreds of calls to `findViewById` for each frame along with a sluggish feeling ListView.

To use the ViewHolder pattern, create a class whose members are the various view elements you need to search for inside of `getView`.

```java
public class ViewHolder {
	TextView text;
	...
}
```

Now we populate our ViewHolder when we first inflate the item's layout.  We can use the View's tag field to give it a reference to our ViewHolder object. Because we are using the view recycling I mentioned earlier, we can retrieve our ViewHolder and reuse it when we are given a previously inflated item view.

```java
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	ViewHolder viewHolder;
	if (convertView == null) {
		convertView = View.inflate(getActivity(), R.layout.item, parent);
		viewHolder = new ViewHolder();
		viewHolder.text = convertView.findViewById(R.id.text_id);
		...
		convertView.setTag(viewHolder);
	} else {
		viewHolder = (ViewHolder)convertView.getTag();
	}
	viewHolder.text.setText("Hello");
	...
	return convertView;
}
```

##Multiple View Layouts

{% include full-blog-image.html src="blogs/2015-11-4-android-listview-guide/backspin-3.jpg" alt="Example of an Android ListView from the Backspin App."  class="right"%}

In the Backspin music player, we often had to have multiple, different item layouts in a single list.  For example, under an artist, there may be a row for an album, rows for all the songs in that album, and then another album row.  Android's Adapter makes handling these cases trivial.  Override the adapter's `getViewTypeCount()` to return the number of unique layouts the view can show.  Then Override `getItemViewType()` to map a position to the index of its view layout.  Android does all of the heavy lifting, and our `getView` will automatically be given a recycled view of the correct layout.

```java
@Override
public int getViewTypeCount() {
	return 2;
}

private static final int ITEM1 = 0;
private static final int ITEM2 = 1;

@Override
public int getItemViewType(int position) {
	if (isItem1(position)) {
		return ITEM1;
	} else {
		return ITEM2;
	}
}
```

##ListView.invalidateViews() vs Adapter.notifyDatasetChanged()

{% include full-blog-image.html src="blogs/2015-11-4-android-listview-guide/backspin-4.jpg" alt="Example of an Android ListView from the Backspin App."%}

So you have made some changes to the data backing a ListView, how do you now get the ListView to draw those changes on screen?  If you look at the Android documentation, the two obvious candidates are `ListView.invalidateViews()` and `Adapter.notifyDatasetChanged()`.  The trick here is that invalidateViews can't observe changes to the Adapter's data and does nothing but redraw the views that are currently on screen.  This means that if you added an item to the Adapter, it will not appear and if you removed an item, it will not disappear.  However, if you want to change the color of the text of your views without touching the data behind them, `ListView.invalidateViews()` may be all that you need.  On the other hand, `notifyDatasetChagned()` tells the Observer watching your adapter to look for changes in the list's data.  After that, the views are redrawn taking the new data into account.  The short answer is that `notifyDatasetChanged` does everything `invalidateViews` does and more, and almost always does everything you are looking for.

##Async Tasks
Your ListView has no hope of performing well if you are doing things like accessing the disk or a database on the main thread inside your adapter's `getView`.  Every time you scroll the list, you are going to block all of the UI logic while you wait for your data to load.  The best solution is to load your data outside of your view logic before you try to display it.  If that is not possible, perhaps in the case of thumbnails, an alternative must be found.  A solution is using AsyncTasks.  AsyncTasks are a simple way to perform slow operations off of the main thread and then display the results on the UI thread.

```java
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	...
	new AsyncTask<Void, Void, Bitmap>() {
		@Override
		public Bitmap doInBackground(Void... params) {
			return BitmapFactory.decodeFile(...);
		}
		@Override
		public void onPostExecute(Bitmap bitmap) {
			imageView.setBitmap(bitmap);
		}
	}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

	return convertView;
}
```

Of course multi-threading is never this easy.  First, this is complicated by the way the adapter recycles list items.  If you start an AsyncTask to modify a view and then that view gets recycled before the Async task ends, the AsnycTask is going to keep running.  When the AsyncTask finishes, it is still going to modify the view even though that view is being used somewhere else entirely.  Another problem is that when scrolling, a new AsyncTask is going to be fired for each view that becomes visible.  This means that if you scroll down and then up, you are potentially going to have two AsyncTasks running for the same item.  All of this can be overcome by keeping track of which AsyncTasks have already been started and making use of `AsyncTask.cancel`.

```java
public class ViewHolder {
	ImageView imageView;
	AsyncTask asyncTask;
	...
}
```

Calls to cancel will let your AsyncTask continue to run, but will prevent `onPostExecute` from being run once it completes.  Note that because `getView` and `onPostExecute` run on the UI thread, we don't need to worry about a race condition here. Now `getView` can look something like this:

```java
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
	...
	if (viewHolder.asyncTask != null) {
		viewHolder.asyncTask.cancel();
	}
	
	viewHolder.asyncTask = new AsyncTask<Void, Void, Bitmap>() {
		@Override
		public Bitmap doInBackground(Void... params) {
			return BitmapFactory.decodeFile(...);
		}
		@Override
		public void onPostExecute(Bitmap bitmap) {
			imageView.setBitmap(bitmap);
		}
	}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

	return convertView;
}
```

Another concern is that you can only have 128 AsyncTasks running at once (with 10 more queued up), so if someone flings through your list quickly and your tasks are too slow, you may run into a `RejectedExecutionException`.  As I mentioned, tasks that have been canceled still run to completion and count against this 138 AsyncTask cutoff until they are done.  A solution here might be to only start a task if the list is scrolling slowly enough that your tasks will have time to finish loading before they are scrolled off the page.  You can look into overriding the `AbsListView.ScrollListener` so that you don't start tasks during quick flings of the ListView.  You should also look into caching the results of your AsyncTasks so you don't have to keep queueing new tasks to load the same data.  Something like Android's [`LRUCache`](http://developer.android.com/reference/android/util/LruCache.html) might be useful here.

Clearly AsyncTasks can be a solution, but they make everything more complicated.  If you are going to use them in ListViews, you need to be mindful of the many ways they can cause problems.

{% include full-blog-image.html src="blogs/2015-11-4-android-listview-guide/backspin-5.jpg" alt="Example of an Android ListView from the Backspin App." %}


##Conclusion
Android Listviews are one of the most commonly used and misused Android UI elements.  Properly implementing them can significantly improve your app's performance and stability.  Do you have other tricks or tips related to Listviews?  If so, please drop us a message and we will include it in this article.  Also, if you are looking for help on your upcoming Android app project, make sure you check out our [Android development services!](https://thebhwgroup.com/services/android-app-development-company-austin-texas)
		]]></description>

    
        <category>Android</category>
    
        <category>ListView</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>Integrating Salesforce into a node application</title>
        <link>https://thebhwgroup.com/blog/integrating-salesforce-node-application</link>
		<author>Taylor Smith</author>
		<pubDate>2015-08-11T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/integrating-salesforce-node-application</guid>
		<description><![CDATA[
		   <p><a href="http://www.salesforce.com/">Salesforce</a> can be a tricky but powerful tool. Using <a href="https://jsforce.github.io/">JSForce</a> and some custom triggers you can integrate Salesforce with your custom <a href="https://nodejs.org/">NodeJS</a>  <a href="https://thebhwgroup.com/services/web-application-development-company-austin-texas">web application</a> for better business management.</p>

<h2>Setting Up</h2>

<p>There are two sides to this application: the NodeJS application, which in our case will be the customer facing side, and the Salesforce side, which will be used to manage the business relations and tracking. Both of these pieces need a little bit of set up before we get started. In this example we will be using NodeJS snippets with the <a href="http://koajs.com/">Koa</a> framework, <a href="http://handlebarsjs.com/">Handlebars</a> for rendering html, and client side interaction written with <a href="http://facebook.github.io/react/">ReactJS</a>. We are also using the <a href="https://babeljs.io/docs/learn-es2015/">es6</a> syntax and are using <a href="https://github.com/babel/gulp-babel">gulp to compile to es5</a>. In the following section we will set up the node application.</p>

<p>Obviously you have to have a Salesforce license to access the Salesforce platform. Once you have the license you can begin by deciding what objects you want to model. Once you log in to Salesforce the main page, you will use is the &quot;Setup&quot; page. You can get to this from the menu on the top right.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/top-links.png" 
      alt="NodeJS Salesforce Top Links"
      
      
       />
      
  </div>
</div>

<p>The &quot;Setup&quot; page is where you will spend most of your time developing for Salesforce. Almost all of the functionality for developing can be found across the bar on the left. Sections can be expanded for more options. I will frequently reference the &quot;Setup&quot; page throughout the guide.</p>

<p>One of the first things you will need to do in Salesforce is create the custom objects. This is fairly simple because there is a wizard used to create custom objects. Often these objects will mirror tables in your local database. As a general rule, when you create objects in Salesforce that will be mirrored in your custom application you will need some way to keep them synced. To keep them synced, you need a shared ID of some sort. This can be stored as an external ID in Salesforce. This external ID can be used for update, insert, and even <a href="https://wiki.postgresql.org/wiki/UPSERT">upsert operations</a>. You can also use the external ID&#39;s to find relationships between objects.</p>

<h3>Some basic routes</h3>

<p>The first part we will set up is our customer facing site. This will be built with NodeJS, Handlebars, and React. In our example, we are adding the ability to add a &quot;Widget&quot; on our site and have that information propagated to Salesforce as a custom object. In order to do this, we will create 2 routes. One for the form to add the widget and a second to save the information. When the information is saved, we use the node JSForce library to send the information to Salesforce.</p>

<p>./src/server.js</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kr">const</span> <span class="nx">koa</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;koa&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">koaBody</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;koa-body&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">logger</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;koa-logger&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">hbs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;koa-hbs&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">router</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;koa-router&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">React</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;react&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">salesForce</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;./salesforce.js&#39;</span><span class="p">);</span>

<span class="kr">const</span> <span class="nx">app</span> <span class="o">=</span> <span class="nx">koa</span><span class="p">();</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="nx">logger</span><span class="p">());</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="nx">router</span><span class="p">(</span><span class="nx">app</span><span class="p">));</span>

<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="nx">hbs</span><span class="p">.</span><span class="nx">middleware</span><span class="p">({</span>
    <span class="nx">defaultLayout</span><span class="o">:</span> <span class="s1">&#39;main&#39;</span><span class="p">,</span>
    <span class="nx">viewPath</span><span class="o">:</span> <span class="nx">__dirname</span> <span class="o">+</span> <span class="s1">&#39;/../views&#39;</span><span class="p">,</span>
    <span class="nx">layoutsPath</span><span class="o">:</span> <span class="nx">__dirname</span> <span class="o">+</span> <span class="s1">&#39;/../views/layouts&#39;</span><span class="p">,</span>
    <span class="nx">partialsPath</span><span class="o">:</span> <span class="nx">__dirname</span> <span class="o">+</span> <span class="s1">&#39;/../views/partials&#39;</span>
<span class="p">}));</span>

<span class="kr">const</span> <span class="nx">WidgetForm</span> <span class="o">=</span> <span class="nx">React</span><span class="p">.</span><span class="nx">createFactory</span><span class="p">(</span><span class="nx">require</span><span class="p">(</span><span class="nx">reactDirectory</span> <span class="o">+</span> <span class="s1">&#39;/widget&#39;</span><span class="p">));</span>

<span class="nx">app</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;/edit-widget&#39;</span><span class="p">,</span> <span class="kd">function</span> <span class="o">*</span> <span class="p">()</span> <span class="p">{</span>
    <span class="k">yield</span> <span class="k">this</span><span class="p">.</span><span class="nx">render</span><span class="p">(</span><span class="s1">&#39;widget-form&#39;</span><span class="p">,</span> <span class="p">{</span>
        <span class="nx">title</span><span class="o">:</span> <span class="s1">&#39;Widget&#39;</span><span class="p">,</span>
        <span class="nx">widgetForm</span><span class="o">:</span> <span class="nx">React</span><span class="p">.</span><span class="nx">renderToString</span><span class="p">(</span><span class="nx">WidgetForm</span><span class="p">())</span>
    <span class="p">});</span>
<span class="p">});</span>

<span class="nx">app</span><span class="p">.</span><span class="nx">post</span><span class="p">(</span><span class="s1">&#39;/save-widget&#39;</span><span class="p">,</span> <span class="nx">koaBody</span><span class="p">(),</span> <span class="kd">function</span> <span class="o">*</span> <span class="p">()</span> <span class="p">{</span>
    <span class="kr">const</span> <span class="nx">widget</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">request</span><span class="p">.</span><span class="nx">body</span><span class="p">;</span>
    <span class="c1">//validate widget - if invalid return errors</span>
    <span class="c1">//save widget to database, add to &quot;widgetContainer&quot; parent container</span>
    <span class="kr">const</span> <span class="nx">savedWidget</span> <span class="o">=</span> <span class="nx">db</span><span class="p">.</span><span class="nx">save</span><span class="p">(</span><span class="nx">widget</span><span class="p">);</span>
    <span class="kr">const</span> <span class="nx">widgetContainer</span> <span class="o">=</span> <span class="nx">getParent</span><span class="p">(</span><span class="nx">widget</span><span class="p">);</span>

    <span class="nx">salesForce</span><span class="p">.</span><span class="nx">addWidget</span><span class="p">(</span><span class="nx">savedWidget</span><span class="p">,</span> <span class="nx">widgetContainer</span><span class="p">.</span><span class="nx">id</span><span class="p">);</span>
<span class="p">});</span>
</code></pre></div>
<p>We use handlebars to handle some of the layouts and script inclusion. This allows for <a href="http://bensmithett.github.io/going-isomorphic-with-react/#/">isomorphic rendering</a> with node and react. Below is the main layout with a section where we can include scripts at the page level.</p>

<p>./views/layouts/main.hbs</p>
<div class="highlight"><pre><code class="language-html" data-lang="html"><span class="cp">&lt;!DOCTYPE html&gt;</span>
<span class="nt">&lt;html&gt;</span>
    <span class="nt">&lt;head&gt;</span>
        <span class="nt">&lt;title&gt;</span>{{title}}<span class="nt">&lt;/title&gt;</span>
        <span class="nt">&lt;meta</span> <span class="na">charset=</span><span class="s">&quot;utf-8&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;meta</span> <span class="na">http-equiv=</span><span class="s">&quot;X-UA-Compatible&quot;</span> <span class="na">content=</span><span class="s">&quot;IE=edge&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no&quot;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;/head&gt;</span>
    <span class="nt">&lt;body&gt;</span>
        {{{body}}}
        {{#block &quot;scripts&quot;}}
        {{/block}}
    <span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>
</code></pre></div>
<h3>Creating a Form to submit</h3>

<p>Now that we have the routes set up and the main layout we can create the form with react. First we create the hbs template for the isomorphic render.</p>

<p>./views/widget-form.hbs</p>
<div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;container&quot;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;add-widget-form&quot;</span><span class="nt">&gt;</span>
        {{{widgetForm}}}
    <span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;/div&gt;</span>

{{#contentFor &quot;scripts&quot;}}
    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span><span class="nt">&gt;</span>
        <span class="nx">React</span><span class="p">.</span><span class="nx">render</span><span class="p">(</span><span class="nx">React</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="nx">Widget</span><span class="p">),</span> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#add-widget-form&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]);</span>
    <span class="nt">&lt;/script&gt;</span>
{{/contentFor}}
</code></pre></div><div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kr">const</span> <span class="nx">React</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;react/addons&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">_</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;lodash&#39;</span><span class="p">);</span>

<span class="kr">const</span> <span class="nx">Widget</span> <span class="o">=</span> <span class="nx">React</span><span class="p">.</span><span class="nx">createClass</span><span class="p">({</span>
    <span class="nx">getInitialState</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="p">{</span>
            <span class="nx">widgetName</span><span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
            <span class="nx">widgetData</span><span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
            <span class="nx">submitting</span><span class="o">:</span> <span class="kc">false</span><span class="p">,</span>
            <span class="nx">errors</span><span class="o">:</span> <span class="p">{},</span>
            <span class="nx">success</span><span class="o">:</span> <span class="kc">false</span>
        <span class="p">};</span>
    <span class="p">},</span>
    <span class="nx">handleWidgetNameChange</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span><span class="nx">widgetName</span><span class="o">:</span> <span class="nx">e</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">value</span><span class="p">,</span> <span class="nx">errors</span><span class="o">:</span> <span class="p">{}});</span>
    <span class="p">},</span>
    <span class="nx">handleWidgetDataChange</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span><span class="nx">widgetData</span><span class="o">:</span> <span class="nx">e</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">value</span><span class="p">,</span> <span class="nx">errors</span><span class="o">:</span> <span class="p">{}});</span>
    <span class="p">},</span>
    <span class="nx">handleSubmit</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
        <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span> <span class="nx">submitting</span><span class="o">:</span> <span class="kc">true</span> <span class="p">});</span>
        <span class="kr">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="nx">_</span><span class="p">.</span><span class="nx">omit</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;errors&#39;</span><span class="p">,</span> <span class="s1">&#39;submitting&#39;</span><span class="p">,</span> <span class="s1">&#39;success&#39;</span><span class="p">]);</span>
        <span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
           <span class="nx">type</span><span class="o">:</span> <span class="s1">&#39;POST&#39;</span><span class="p">,</span>
           <span class="nx">url</span><span class="o">:</span> <span class="s1">&#39;/save-widget&#39;</span><span class="p">,</span>
           <span class="nx">data</span><span class="o">:</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">data</span><span class="p">),</span>
           <span class="nx">dataType</span><span class="o">:</span> <span class="s1">&#39;json&#39;</span><span class="p">,</span>
           <span class="nx">contentType</span><span class="o">:</span> <span class="s1">&#39;application/json; charset=utf-8&#39;</span>
           <span class="p">}).</span><span class="nx">done</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
              <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span> <span class="nx">submitting</span><span class="o">:</span> <span class="kc">false</span><span class="p">,</span> <span class="nx">success</span><span class="o">:</span> <span class="kc">true</span><span class="p">,</span> <span class="nx">errors</span><span class="o">:</span> <span class="p">{}</span> <span class="p">});</span>
           <span class="p">}).</span><span class="nx">fail</span><span class="p">(</span><span class="nx">result</span> <span class="o">=&gt;</span> <span class="p">{</span>
              <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span> <span class="nx">submitting</span><span class="o">:</span> <span class="kc">false</span> <span class="p">});</span>
              <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">isMounted</span><span class="p">()</span> <span class="o">&amp;&amp;</span> <span class="nx">result</span><span class="p">.</span><span class="nx">responseJSON</span><span class="p">.</span><span class="nx">validationResult</span><span class="p">)</span> <span class="p">{</span>
                 <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span> <span class="nx">errors</span><span class="o">:</span> <span class="nx">result</span><span class="p">.</span><span class="nx">responseJSON</span><span class="p">.</span><span class="nx">validationResult</span> <span class="p">});</span>
              <span class="p">}</span>
           <span class="p">});</span>
      <span class="p">},</span>
       <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
          <span class="k">return</span> <span class="p">(</span>
             <span class="o">&lt;</span><span class="nx">div</span> <span class="nx">className</span><span class="o">=</span><span class="s2">&quot;widget-form-container&quot;</span><span class="o">&gt;</span>
             <span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">success</span> <span class="o">?</span>
                <span class="o">&lt;</span><span class="nx">h3</span> <span class="nx">className</span><span class="o">=</span><span class="s1">&#39;success&#39;</span><span class="o">&gt;</span>
                   <span class="nx">Widget</span> <span class="nx">Saved</span><span class="o">!</span>
                <span class="o">&lt;</span><span class="err">/h3&gt;</span>
             <span class="o">:</span> <span class="o">&lt;</span><span class="nx">h3</span><span class="o">&gt;</span>
                <span class="nx">Add</span> <span class="nx">Widget</span>
             <span class="o">&lt;</span><span class="err">/h3&gt;}</span>
             <span class="o">&lt;</span><span class="nx">div</span> <span class="nx">className</span><span class="o">=</span><span class="s2">&quot;error-info&quot;</span><span class="o">&gt;</span>
                <span class="o">&lt;</span><span class="nx">ul</span> <span class="nx">className</span><span class="o">=</span><span class="p">{(</span><span class="nx">_</span><span class="p">.</span><span class="nx">size</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">errors</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">?</span> <span class="s1">&#39;hide&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">_</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">errors</span><span class="p">,</span> <span class="p">(</span><span class="nx">v</span><span class="p">,</span> <span class="nx">k</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="o">&lt;</span><span class="nx">li</span> <span class="nx">key</span><span class="o">=</span><span class="p">{</span><span class="nx">k</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">v</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/li&gt;)}&lt;/ul&gt;</span>
             <span class="o">&lt;</span><span class="err">/div&gt;</span>
             <span class="o">&lt;</span><span class="nx">form</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;widget-form&#39;</span> <span class="o">+</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">success</span> <span class="o">?</span> <span class="s1">&#39; hide&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">)}</span> <span class="nx">onSubmit</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">handleSubmit</span><span class="p">}</span> <span class="o">&gt;</span>
             <span class="o">&lt;</span><span class="nx">div</span> <span class="nx">className</span><span class="o">=</span><span class="s2">&quot;input-row&quot;</span><span class="o">&gt;</span>
                <span class="o">&lt;</span><span class="nx">label</span> <span class="nx">htmlFor</span><span class="o">=</span><span class="s1">&#39;title_copy&#39;</span><span class="o">&gt;</span><span class="nx">Widget</span> <span class="nx">Name</span><span class="o">&lt;</span><span class="err">/label&gt;</span>
                <span class="o">&lt;</span><span class="nx">input</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">errors</span><span class="p">.</span><span class="nx">widgetName</span> <span class="o">?</span> <span class="s1">&#39;error&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span> <span class="nx">name</span><span class="o">=</span><span class="s1">&#39;widgetName&#39;</span> <span class="nx">defaultValue</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">widgetName</span><span class="p">}</span> <span class="nx">onChange</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">handleWidgetNameChange</span><span class="p">}</span> <span class="nx">type</span><span class="o">=</span><span class="s1">&#39;text&#39;</span> <span class="nx">autofocus</span> <span class="o">/&gt;</span>
             <span class="o">&lt;</span><span class="err">/div&gt;</span>
             <span class="o">&lt;</span><span class="nx">div</span> <span class="nx">className</span><span class="o">=</span><span class="s2">&quot;input-row&quot;</span><span class="o">&gt;</span>
                <span class="o">&lt;</span><span class="nx">label</span> <span class="nx">htmlFor</span><span class="o">=</span><span class="s1">&#39;title_copy&#39;</span><span class="o">&gt;</span><span class="nx">Widget</span> <span class="nx">Data</span><span class="o">&lt;</span><span class="err">/label&gt;</span>
                <span class="o">&lt;</span><span class="nx">input</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">errors</span><span class="p">.</span><span class="nx">widgetData</span> <span class="o">?</span> <span class="s1">&#39;error&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span> <span class="nx">name</span><span class="o">=</span><span class="s1">&#39;widgetData&#39;</span> <span class="nx">defaultValue</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">widgetData</span><span class="p">}</span> <span class="nx">onChange</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">handleWidgetDataChange</span><span class="p">}</span> <span class="nx">type</span><span class="o">=</span><span class="s1">&#39;text&#39;</span> <span class="o">/&gt;</span>
             <span class="o">&lt;</span><span class="err">/div&gt;</span>
             <span class="o">&lt;</span><span class="nx">div</span> <span class="nx">className</span><span class="o">=</span><span class="s1">&#39;input-wrap&#39;</span><span class="o">&gt;</span>
                <span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">submitting</span> <span class="o">?</span>
                   <span class="o">&lt;</span><span class="nx">i</span> <span class="nx">className</span><span class="o">=</span><span class="s2">&quot;fa fa-spinner fa-spin fa-3x&quot;</span><span class="o">&gt;&lt;</span><span class="err">/i&gt;:</span>
                   <span class="o">&lt;</span><span class="nx">input</span> <span class="nx">type</span><span class="o">=</span><span class="s1">&#39;submit&#39;</span> <span class="nx">name</span><span class="o">=</span><span class="s1">&#39;Save Widget&#39;</span> <span class="nx">value</span><span class="o">=</span><span class="s1">&#39;Save Changes&#39;</span> <span class="o">/&gt;</span>
                 <span class="p">}</span>
             <span class="o">&lt;</span><span class="err">/div&gt;</span>
          <span class="o">&lt;</span><span class="err">/form&gt;</span>
        <span class="o">&lt;</span><span class="err">/div&gt;</span>
      <span class="p">);</span>
   <span class="p">}</span>
<span class="p">});</span>

<span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nx">Widget</span><span class="p">;</span>

<span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nb">window</span> <span class="o">!==</span> <span class="s1">&#39;undefined&#39;</span><span class="p">)</span> <span class="p">{</span>
   <span class="nb">window</span><span class="p">.</span><span class="nx">Widget</span> <span class="o">=</span> <span class="nx">Widget</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p>At this point the application should be functioning with a page to add widgets. This guide doesn&#39;t focus on the node side of this as I would like to cover more of the interaction with Salesforce.</p>

<h3>Converting to Salesforce Objects</h3>

<p>Salesforce uses Objects to do most of the work. Everything from contacts to purchases is modeled by an object. In order to represent our Widgets we will need to create a custom object. To do this go to the &quot;Setup&quot; page and click on the &quot;Create&quot; tab on the left to reveal the link to &quot;Objects&quot;.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/build-create-link-objects.png" 
      alt="Salesforce Build Create Links"
      
      
       />
      
  </div>
</div>

<p>You can then click &quot;New Custom Object&quot;.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/custom-objects.png" 
      alt="Salesforce Custom Object Page"
      
      
       />
      
  </div>
</div>

<p>This wizard is simple enough, just be aware of the name that the Salesforce API will be using is generated as a part of this process as the &quot;Object Name&quot; field.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/custom-object-form.png" 
      alt="Salesforce Create custom object form"
      
      
       />
      
  </div>
</div>

<p>The process of figuring out API information can be a little daunting at first because finding the correct names and the relations between objects can be difficult to understand. JSForce provides a <a href="https://jsforce.github.io/document/#describe">describe query</a> that can help you to find this information. You can also find information by browsing the objects on the Salesforce site. They provide a &quot;Schema Builder&quot; tool (found on the &quot;Objects&quot; page) to view the relations between objects.
In our example, we create a Widget object and a parent container for the widgets to demonstrate how to handle relations. So we created a new custom object and gave it a few fields including a name, a custom data field, and a field to tell if it had been sold. To create the relationship, we create a lookup field to the parent object. Lastly, we make sure that the API names are correct so we can use them for the JSForce queries.</p>

<h3>JSForce</h3>

<p>JSForce allows us to communicate from our node application to the Salesforce platform. Once you enter your account information for the connection, you can begin using their API to access Salesforce. The JSForce API allows us to access the Salesforce SOAP API through a neatly packaged javascript library. The JSForce documentation covers the main operations that will be used including CRUD operations, querying, and search. The describe and identity functions are also helpful for finding information about objects in Salesforce.
Once we have the necessary information we can build the interaction from our site to Salesforce.</p>

<h4>Sending data to Salesforce</h4>

<p>We created a separate module for any queries to Salesforce. Using the upsert, we can call this code for either insert or update of records, if we are given the external ID. For more examples, you can look at the <a href="https://jsforce.github.io/document/">JSForce documentation</a>.</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kr">const</span> <span class="nx">jsforce</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;jsforce&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">jsConn</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">jsforce</span><span class="p">.</span><span class="nx">Connection</span><span class="p">();</span>

<span class="c1">//From: https://jsforce.github.io/document/#connection</span>
<span class="nx">jsConn</span><span class="p">.</span><span class="nx">login</span><span class="p">(</span><span class="s1">&#39;&lt;salesforce username&gt;&#39;</span><span class="p">,</span> <span class="s1">&#39;&lt;salesforce password&gt;&#39;</span><span class="p">);</span>


<span class="nx">module</span><span class="p">.</span><span class="nx">exports</span><span class="o">=</span> <span class="p">{</span>
   <span class="nx">addWidget</span><span class="p">(</span><span class="nx">widget</span><span class="p">,</span> <span class="nx">widgetParentId</span><span class="p">){</span>
      <span class="kr">const</span> <span class="nx">widgetContainer</span> <span class="o">=</span> <span class="k">yield</span> <span class="nx">jsConn</span><span class="p">.</span><span class="nx">sobject</span><span class="p">(</span><span class="s1">&#39;pba__WidgetContainer__c&#39;</span><span class="p">).</span><span class="nx">select</span><span class="p">(</span><span class="s1">&#39;*&#39;</span><span class="p">).</span><span class="nx">where</span><span class="p">({</span><span class="nx">External_ID__c</span><span class="o">:</span> <span class="nx">widgetParentId</span><span class="p">});</span>
      <span class="kr">const</span> <span class="nx">widgetSF</span> <span class="o">=</span> <span class="p">{</span>
         <span class="nx">Name</span><span class="o">:</span> <span class="nx">widget</span><span class="p">.</span><span class="nx">name</span><span class="p">,</span>
         <span class="nx">Custom_Field__c</span><span class="o">:</span> <span class="nx">widget</span><span class="p">.</span><span class="nx">custom_data</span><span class="p">,</span>
         <span class="nx">External_ID__c</span><span class="o">:</span> <span class="nx">widget</span><span class="p">.</span><span class="nx">id</span><span class="p">,</span>
         <span class="nx">Widget_Container__c</span><span class="o">:</span> <span class="nx">widgetContainer</span><span class="p">.</span><span class="nx">Id</span>
      <span class="p">};</span>
      <span class="k">return</span> <span class="k">yield</span> <span class="nx">jsConn</span><span class="p">.</span><span class="nx">sobject</span><span class="p">(</span><span class="s1">&#39;pba__Widget__c&#39;</span><span class="p">).</span><span class="nx">upsert</span><span class="p">(</span><span class="nx">widgetSF</span><span class="p">,</span> <span class="s1">&#39;External_ID__c&#39;</span><span class="p">);</span>
   <span class="p">}</span>
<span class="p">};</span>
</code></pre></div>
<h4>Getting Results Back from Salesforce</h4>

<p>The result that you get back from Salesforce can be used for error checking and for getting more information. You can request other information like the Salesforce ID. The errors that are returned are helpful in diagnosing problems with queries, variable naming, or even with types of data.</p>

<h3>How Does Salesforce Communicate Out?</h3>

<p>One way to send messages and data out is to use triggers. Triggers respond to changes on Salesforce Objects and can be used to call Apex code. Apex code in turn can then send outbound http requests. Apex provides this functionality through the HttpRequest class.</p>

<h4>Dev Sandbox and Deploys</h4>

<p>In order to develop any Apex code you must first create a development sandbox. This can be found by going to the &quot;Setup&quot; page and then to the &quot;Sandboxes&quot; Page.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/deploy-links.png" 
      alt="Salesforce deploy links"
      
      
       />
      
  </div>
</div>

<p>Any code that you develop as an Apex class or trigger is created here. Salesforce provides a useful developers console that features syntax highlighting, autocompletion, and predictive suggestions. These can be very helpful when developing with Apex Libraries.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/developer-console.png" 
      alt="Salesforce developer console example"
      
      
       />
      
  </div>
</div>

<p>The process for deploying from the sandbox can be a little confusing though. Once you have finished your code, sufficiently tested it, and are ready to deploy, you can follow these steps:</p>

<p>1.Create an outbound change set by going to the &quot;Setup&quot; page and clicking &quot;Outbound Change Sets&quot; under the &quot;Deploy&quot; section on the left.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/new-changeset.png" 
      alt="Link to new change set"
      
      
       />
      
  </div>
</div>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/name-outbound-change-set.png" 
      alt="Naming the outbound change set"
      
      
       />
      
  </div>
</div>

<p>2.Add components to the change set. You can also check the option to add any dependencies. This will include any Objects, Classes, or other related code that is used in the element that you are adding. This can be useful to ensure that any custom fields or objects used to create the trigger will be included in the change set.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/outbound-change-set-add-elements.png" 
      alt="Add components to Change Set"
      
      
       />
      
  </div>
</div>

<p>3.Once all of the elements are added, click &quot;Upload&quot; to finish the development side of the deploy.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/outbound-change-set-upload.png" 
      alt="Upload outbound change set"
      
      
       />
      
  </div>
</div>

<p>4.Switch back to the production site and go to the &quot;Setup&quot; page.
5.On the &quot;Setup&quot; page in the &quot;Deploy&quot; section select &quot;Inbound Change Sets&quot;.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/change-sets-awaiting-deployment.png" 
      alt="Change sets awaiting deployment"
      
      
       />
      
  </div>
</div>

<p>6.At this point you should see the change set in the &quot;Change Sets Awaiting Deployment&quot; section. There is a link to deploy the change set that you should click to finish the process.</p>

<p>If your code did not contain tests, the deploy will fail and alert you to the required coverage for test cases. If your code has tests, is valid, and the deploy succeeds, it will eventually show up in the &quot;Deployed Change Sets&quot; Section and will be currently active. The changes can take up to 30 minutes to propagate after this process, so testing is essential for saving time and effort. Also, you can save a lot of time during the deploy if you use the developer console to catch errors and run tests before the deploy.</p>

<h4>Preparing for a Trigger</h4>

<p>Creating the trigger is fairly straightforward. Salesforce documentation can be lacking, but there are plenty of examples online. For our purposes, we need the trigger to make calls out. Unfortunately this is not allowed directly from the trigger. In order to make calls out, you have to create a separate class to send http requests.
You can get to triggers and classes on the &quot;Setup&quot; page by expanding the &quot;Develop&quot; tab under the &quot;Build&quot; section.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/build-develop-links-classes-triggers.png" 
      alt="Salesforce build develop links"
      
      
       />
      
  </div>
</div>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">WidgetOutbound</span> <span class="o">{</span>
   <span class="nd">@future</span> <span class="o">(</span><span class="n">callout</span><span class="o">=</span><span class="kc">true</span><span class="o">)</span>
   <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">widgetSold</span><span class="o">(</span><span class="n">Integer</span> <span class="n">widgetId</span><span class="o">,</span> <span class="n">Integer</span> <span class="n">widgetContainerId</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">HttpRequest</span> <span class="n">req</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">HttpRequest</span><span class="o">();</span>
      <span class="n">HttpResponse</span> <span class="n">res</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">HttpResponse</span><span class="o">();</span>
      <span class="n">Http</span> <span class="n">http</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">Http</span><span class="o">();</span>
      <span class="n">req</span><span class="o">.</span><span class="na">setEndpoint</span><span class="o">(</span><span class="err">&#39;</span><span class="nl">https:</span><span class="c1">//oursite.com/widget-sold&#39;);</span>
      <span class="n">req</span><span class="o">.</span><span class="na">setMethod</span><span class="o">(</span><span class="err">&#39;</span><span class="n">POST</span><span class="err">&#39;</span><span class="o">);</span>
      <span class="n">req</span><span class="o">.</span><span class="na">setHeader</span><span class="o">(</span><span class="err">&#39;</span><span class="n">Content</span><span class="o">-</span><span class="n">type</span><span class="sc">&#39;,&#39;</span><span class="n">application</span><span class="o">/</span><span class="n">json</span><span class="err">&#39;</span><span class="o">);</span>
      <span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Integer</span><span class="o">&gt;</span> <span class="n">mapBody</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Integer</span><span class="o">&gt;();</span>
      <span class="n">mapBody</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="err">&#39;</span><span class="n">widget_id</span><span class="err">&#39;</span><span class="o">,</span> <span class="n">widgetId</span><span class="o">);</span>
      <span class="n">mapBody</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="err">&#39;</span><span class="n">widget_container_id</span><span class="err">&#39;</span><span class="o">,</span> <span class="n">widgetContainerId</span><span class="o">);</span>
      <span class="n">String</span> <span class="n">jsonString</span> <span class="o">=</span> <span class="n">JSON</span><span class="o">.</span><span class="na">serialize</span><span class="o">(</span><span class="n">mapBody</span><span class="o">);</span>
      <span class="n">req</span><span class="o">.</span><span class="na">setBody</span><span class="o">(</span><span class="n">jsonString</span><span class="o">);</span>
      <span class="k">try</span> <span class="o">{</span>
         <span class="n">res</span> <span class="o">=</span> <span class="n">http</span><span class="o">.</span><span class="na">send</span><span class="o">(</span><span class="n">req</span><span class="o">);</span>
      <span class="o">}</span> <span class="k">catch</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">CalloutException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
         <span class="n">System</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="err">&#39;</span><span class="n">Callout</span> <span class="nl">Error:</span> <span class="err">&#39;</span> <span class="o">+</span> <span class="n">e</span><span class="o">);</span>
         <span class="n">System</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="n">res</span><span class="o">.</span><span class="na">toString</span><span class="o">());</span>
      <span class="o">}</span>
   <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<h4>Creating the trigger</h4>

<p>Now that we have the outbound class, we can create the trigger that calls it. Keep in mind that triggers can fire on many different events and are not limited to &quot;before update&quot;.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">trigger</span> <span class="n">update_widget</span> <span class="n">on</span> <span class="nf">pba__Widget__c</span> <span class="o">(</span><span class="n">before</span> <span class="n">update</span><span class="o">)</span> <span class="o">{</span>
   <span class="k">for</span><span class="o">(</span><span class="n">pba__Widget__c</span> <span class="n">newWidget</span> <span class="o">:</span> <span class="n">Trigger</span><span class="o">.</span><span class="na">new</span> <span class="o">)</span> <span class="o">{</span>
      <span class="n">pba__Widget__c</span> <span class="n">oldWidget</span> <span class="o">=</span> <span class="n">Trigger</span><span class="o">.</span><span class="na">oldMap</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">newWidget</span><span class="o">.</span><span class="na">Id</span><span class="o">);</span>
      <span class="n">Boolean</span> <span class="n">widgetSoldStatusChanged</span> <span class="o">=</span> <span class="o">!(</span><span class="n">oldWidget</span><span class="o">.</span><span class="na">Widget_Sold__c</span> <span class="o">==</span> <span class="n">newWidget</span><span class="o">.</span><span class="na">Widget_Sold__c</span><span class="o">);</span>
      <span class="k">if</span><span class="o">(</span><span class="n">widgetSoldStatusChanged</span> <span class="o">&amp;&amp;</span> <span class="n">newWidget</span><span class="o">.</span><span class="na">Widget_Sold__c</span><span class="o">)</span> <span class="o">{</span>
         <span class="n">System</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="err">&#39;</span><span class="n">Widget</span> <span class="nl">Trigger:</span> <span class="n">Widget</span> <span class="n">Sold</span><span class="o">!</span><span class="err">&#39;</span><span class="o">);</span>
         <span class="n">WidgetOutbound</span><span class="o">.</span><span class="na">widgetSold</span><span class="o">(</span><span class="n">newWidget</span><span class="o">.</span><span class="na">external_ID__c</span><span class="o">.</span><span class="na">intValue</span><span class="o">(),</span> <span class="n">newWidget</span><span class="o">.</span><span class="na">RR_Postgres_Account_Id__c</span><span class="o">.</span><span class="na">intValue</span><span class="o">());</span>
      <span class="o">}</span>
   <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<h4>Writing Tests</h4>

<p>Salesforce requires that any classes and triggers that you write include test cases. These tests are run before deploying from the sandbox to the production site. Some examples of tests follow:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="nd">@isTest</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestWidgetOutbound</span> <span class="o">{</span>
   <span class="kd">public</span> <span class="kd">static</span> <span class="n">testMethod</span> <span class="kt">void</span> <span class="nf">testWidgetSold</span><span class="o">()</span> <span class="o">{</span>
      <span class="n">Test</span><span class="o">.</span><span class="na">setMock</span><span class="o">(</span><span class="n">HttpCalloutMock</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="k">new</span> <span class="nf">WidgetWebServiceCalloutMock</span><span class="o">());</span>
      <span class="n">WidgetOutbound</span><span class="o">.</span><span class="na">widgetSold</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span><span class="mi">1</span><span class="o">);</span>
   <span class="o">}</span>

   <span class="kd">public</span> <span class="kd">static</span> <span class="n">testMethod</span> <span class="kt">void</span> <span class="nf">testWidgetUpdateTrigger</span><span class="o">(){</span>
      <span class="n">Test</span><span class="o">.</span><span class="na">setMock</span><span class="o">(</span><span class="n">HttpCalloutMock</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="k">new</span> <span class="nf">WidgetWebServiceCalloutMock</span><span class="o">());</span>
      <span class="n">pba__Widget__c</span> <span class="n">testWidget</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">pba__Widget__c</span><span class="o">(</span> <span class="n">Name</span> <span class="o">=</span> <span class="err">&#39;</span><span class="n">Apex</span> <span class="n">Test</span> <span class="n">Widget</span><span class="err">&#39;</span><span class="o">,</span> <span class="nl">Custom_Field__c:</span> <span class="err">&#39;</span><span class="n">test</span> <span class="n">data</span><span class="err">&#39;</span><span class="o">,</span> <span class="nl">External_ID__c:</span> <span class="mi">1</span><span class="o">,</span> <span class="nl">Widget_Sold__c:</span> <span class="err">&#39;</span><span class="n">No</span><span class="err">&#39;</span><span class="o">);</span>
      <span class="n">insert</span> <span class="n">testWidget</span><span class="o">;</span>
      <span class="n">pba__Widget__c</span> <span class="n">testWidget2</span> <span class="o">=</span> <span class="o">[</span><span class="n">SELECT</span> <span class="n">Id</span> <span class="n">FROM</span> <span class="n">pba__Widget__c</span> <span class="n">WHERE</span> <span class="n">Name</span> <span class="o">=</span> <span class="err">&#39;</span><span class="n">Apex</span> <span class="n">Test</span> <span class="n">Listing</span><span class="err">&#39;</span> <span class="n">LIMIT</span> <span class="mi">1</span><span class="o">];</span>
      <span class="n">testListing2</span><span class="o">.</span><span class="na">Widget_Sold__c</span> <span class="o">=</span> <span class="err">&#39;</span><span class="n">Sold</span><span class="err">&#39;</span><span class="o">;</span>
      <span class="n">update</span> <span class="n">testListing2</span><span class="o">;</span>
      <span class="n">delete</span> <span class="n">testListing2</span><span class="o">;</span>
   <span class="o">}</span>
<span class="o">}</span>

<span class="nd">@isTest</span>
<span class="n">global</span> <span class="kd">class</span> <span class="nc">WidgetWebServiceCalloutMock</span> <span class="kd">implements</span> <span class="n">HttpCalloutMock</span> <span class="o">{</span>
   <span class="n">global</span> <span class="n">HTTPResponse</span> <span class="nf">respond</span><span class="o">(</span><span class="n">HTTPRequest</span> <span class="n">req</span><span class="o">)</span> <span class="o">{</span>
      <span class="c1">// Create a fake response,</span>
      <span class="c1">// Set response values, and</span>
      <span class="c1">// return response.</span>
      <span class="n">HttpResponse</span> <span class="n">res</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">HttpResponse</span><span class="o">();</span>
      <span class="n">res</span><span class="o">.</span><span class="na">setHeader</span><span class="o">(</span><span class="err">&#39;</span><span class="n">Content</span><span class="o">-</span><span class="n">Type</span><span class="err">&#39;</span><span class="o">,</span> <span class="err">&#39;</span><span class="n">application</span><span class="o">/</span><span class="n">json</span><span class="err">&#39;</span><span class="o">);</span>
      <span class="n">res</span><span class="o">.</span><span class="na">setBody</span><span class="o">(</span><span class="err">&#39;</span><span class="o">{</span><span class="s">&quot;foo&quot;</span><span class="o">:</span><span class="s">&quot;bar&quot;</span><span class="o">}</span><span class="err">&#39;</span><span class="o">);</span>
      <span class="n">res</span><span class="o">.</span><span class="na">setStatusCode</span><span class="o">(</span><span class="mi">200</span><span class="o">);</span>
      <span class="k">return</span> <span class="n">res</span><span class="o">;</span>
   <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<h3>Responding to the Trigger</h3>

<p>Handling the responses is easy because they can be handled like any other asynchronous request. With koaBody we can parse the results and store the information accordingly. This can be used to update the database, send emails, or change the business workflow. The basic code follows this structure:</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">app</span><span class="p">.</span><span class="nx">post</span><span class="p">(</span><span class="s1">&#39;/salesforce/widgetTrigger&#39;</span><span class="p">,</span> <span class="nx">koaBody</span><span class="p">(),</span> <span class="kd">function</span> <span class="o">*</span> <span class="p">()</span> <span class="p">{</span>
   <span class="kr">const</span> <span class="nx">details</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">request</span><span class="p">.</span><span class="nx">body</span><span class="p">;</span>
   <span class="c1">//handle details about widget</span>
   <span class="k">this</span><span class="p">.</span><span class="nx">status</span> <span class="o">=</span> <span class="mi">200</span><span class="p">;</span>
<span class="p">});</span>
</code></pre></div>
<h3>Gotchas and other notes</h3>

<p>There are a couple things to watch out for when using Salesforce. At times, the Salesforce API can be really slow. Average request times can be up to 3 seconds for simple operations. Below are some other issues that can be addressed if they come up.</p>

<h4>Whitelisting Outbound Traffic</h4>

<p>A big gotcha of Salesforce is that outbound traffic must be whitelisted. This means that we need to whitelist our site by url so that Salesforce doesn&#39;t reject all of our outbound requests. This can be found on the &quot;Setup&quot; page under Administer. Expand the &quot;Security Controls&quot; section and click &quot;Remote Site Settings&quot;. There is a wizard to add a &quot;New Remote Site&quot; from this page that will approve any site that you want to send messages to.</p>

<h4>Catching Errors with Logs</h4>

<p>A good way of ensuring that your application is working properly is by using logs. One trick we found helpful was to have the website login through JSForce/Salesforce as a unique user. That way we could track any changes made by the site. It also allows debug logs to be tracked by user. On the &quot;Setup&quot; page near the bottom on the left is a section for &quot;Monitoring&quot;.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/monitor-logs-link-logs.png" 
      alt="Salesforce Monitor Logs Links"
      
      
       />
      
  </div>
</div>

<p>If you expand the &quot;Logs&quot; section, you can find the &quot;Debug Logs&quot;. By clicking on this, you can see that Salesforce generates many logs even through normal operation.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/debug-logs-list.png" 
      alt="Salesforce Debug Log List"
      
      
       />
      
  </div>
</div>

<p>You can limit what you see and filter it to specific users which will let you see specific errors or problems. This can be useful to figure out where a trigger is failing or what information the trigger is seeing on the fire event.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/debug-logs-users.png" 
      alt="Salesforce debug log user filters"
      
      
       />
      
  </div>
</div>

<h2>Conclusion</h2>

<p>Hopefully at this point you have a working application that communicates with Salesforce. This can be a tricky process and hopefully I have provided enough resources for you to get this working. Unfortunately, the documentation for Salesforce can be a bit lacking at times, and because of the recent move to &quot;Force.com&quot;, many articles are no longer hosted at the same urls.</p>

<h2>Other libraries</h2>

<ul>
<li><a href="https://fontawesome.com/">Font Awesome</a> - spinners and other small graphics</li>
<li><a href="https://github.com/alexmingoia/koa-router">Koa Router</a> - handle gets and posts</li>
<li><a href="https://github.com/dlau/koa-body">koaBody</a> - parse http body as a koa middleware</li>
</ul>

		]]></description>

    
        <category>NodeJS</category>
    
        <category>salesforce</category>
    
        <category>javascript</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>Isomorphic Web Design with React and Scala</title>
        <link>https://thebhwgroup.com/blog/isomorphic-web-design-react-scala</link>
		<author>Brett Burnett</author>
		<pubDate>2015-06-23T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/isomorphic-web-design-react-scala</guid>
		<description><![CDATA[
		   <h2>Isomorphic Web Design with React and Scala</h2>

<p>Isomorphic web design is an approach to <a href="https://thebhwgroup.com/services/web-application-development-company-austin-texas" target="_blank">web development</a> that is gathering momentum.  The concept of Isomorphic web design is simple, dynamically generate HTML using either server or client rendering based on which approach yields the best experience for our audience.  Server rendered content is very fast if built correctly; however, client rendered <a href="https://en.wikipedia.org/wiki/Single-page_application">Single Page Applications</a> (SPA&#39;s) have shown that they can offer faster page transitions leading to a more engaging user experience.  Users typically equate the experience of using a SPA with mobile apps or desktop applications.  Popular web-based e-mail clients like <a href="https://mail.google.com">Gmail</a> and <a href="https://mail.office365.com">Outlook 365</a> are textbook examples of well written SPA&#39;s.  Users of these systems can fluidly navigate between reading, composing, searching, and managing e-mail without the jarring page flashes and loading delays associated with a typical server rendered web application.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/react_logo.png" 
      alt="Isomorphic Web Design with React"
      
      
       />
      
  </div>
</div>

<p>Isomorphic web design is a great architecture option on its own, but it&#39;s recent growth is driven by the success of SPAs and their two primary disadvantages, Search Engine Optimization (SEO) and initial page load performance.  These two challenges are the principal reason many SPA developers are looking to Isomorphic web design for solutions.  Today we&#39;ll discuss how <a href="http://facebook.github.io/react">React</a> can solve these challenges.  We&#39;ll also review a simple <a href="http://www.scala-lang.org">Scala</a> website sample that demonstrates how React can be integrated into the server to accomplish true Isomorphic web design.  The code presnted in this article is posted on <a href="https://github.com/bhw/react-scala-isomorphic">github</a> if you want to follow along.</p>

<h3>Single Page Application SEO Challenges</h3>

<p>SPAs face a difficult challenge when it comes to SEO.  <a href="http://googlewebmastercentral.blogspot.com/2014/05/understanding-web-pages-better.html">Until recently</a>, Google&#39;s search index crawler would not execute JavaScript when analyzing web pages.  As of June 2015, Bing (and Yahoo) have not publicly indicated similar support for JavaScript.  Although Google changed their JavaScript limitation, it&#39;s still unclear how much JavaScript the Google crawler executes and how effective or accurate the crawler is in determining the true intent of the JavaScript generated content.  Any website that carefully manages its SEO would have reservations about using a SPA due to the risk that Google might incorrectly score their content and adversely impact their domain or page rank.  The best practice for an SEO dependent site is to follow traditional <a href="https://thebhwgroup.com/services/website-design-company-austin-texas" target="_blank">web design</a> using server generated HTML, allowing businesses to carefully control their SEO content while ensuring their intent is properly understood by Google.  Websites that want to utilize SPAs to provide an engaging user experience without impacting their SEO are left in a difficult situation.  Some enterprising developers have developed solutions using <a href="https://github.com/meanjs/mean-seo">PhantomJS</a> based on a proposal by <a href="http://googlewebmastercentral.blogspot.com.au/2009/10/proposal-for-making-ajax-crawlable.html">Google</a> but this solution is far from ideal as well as being difficult to setup and maintain.</p>

<h3>Single Page Application SEO Performance Challenges</h3>

<p>The second challenge faced by SPAs is how to provide an optimized experience during the initial page load.  Because SPAs utilize JavaScript to render on the client, they must load and execute all the included script files, possibly make a second call for data, and then render the results.  All of these steps must be completed before a user can be shown content.  SPA developers are familiar with the dreaded <strong>FOUC</strong> (flash of un-styled content) that can occur while a SPA page is being loaded and scripts have yet to execute.  A second concern with page speed is also related to a Google decision.  In 2014, Google made headlines when they announced that page load performance would be a factor in their algorithm to determine page rank.  This policy change meant that quickly loading websites would be preferred to websites that load more slowly.  Today, Google provides a handy <a href="https://developers.google.com/speed/pagespeed">page speed test</a> for designers to analyze performance as seen by the Google crawler.</p>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/google-page-speed.png" 
      alt="Google Page Speed Insights"
      
      
       />
      
  </div>
</div>

<p>Unfortunately SPAs are heavily penalized in this new scoring algorithm.  A traditional website renders on a server and returns HTML suitable for indexing by Google.  A SPA works entirely differently and must first load and execute a significant amount of JavaScript in the user&#39;s browser, make a second request to the server for data to render, and use client processing power and resources to produce HTML.  Google&#39;s crawler counts all this extra work and delay against the page load time and scores SPAs lower than traditional websites.  For comparison, a SPA might take 800 ms or more to render, compared to a traditional web server that might render the same content in 200 ms or less.  Obviously, once the SPA is loaded, it will be much faster than a traditional server rendered website when navigating to other pages, but Google only considers the initial page load performance, not the user&#39;s observed performance when browsing multiple pages.</p>

<h3>Isomorphic Solution for SEO and Page Speed</h3>

<p>SPA developers understand that a new approach is necessary to utilize a SPA architecture while maintaining SEO and initial page load performance.  Isomorphic web development is a popular solution that many developers are embracing.  In an Isomorphic web app, the developer writes a SPA that renders HTML on the client, but is also capable of executing on the server to render content for the initial page load.  Most isomorphic web applications accomplish this by using a shared code base between the server and client.  Usually a server-side JavaScript engine like <a href="https://nodejs.org">Node.js</a> is used to pre-render the page for the client.  In an Isomorphic website, server rendered HTML is returned to the client on the first page request.  The HTML contains special markup that allows an asynchronously loaded client-side SPA to attach and handle future rendering on the client.  As the user changes views or pages, the client-side SPA completely takes over navigation and rendering, only using the server for API requests as needed.  In our sample today, we&#39;re going to use React for both client and server rendering.  The following illustration demonstrates how our Isomorphic React application compares to a traditional server rendered application and a SPA like <a href="https://angularjs.org">AngularJS</a> or <a href="http://emberjs.com">Ember.js</a>.</p>

<p><img src="https://thebhwgroup.com/sites/default/images/page-speed.png" srcset="https://thebhwgroup.com/sites/default/images/page-speed.png 1x, https://thebhwgroup.com/sites/default/images/page-speed-1600.png 2x" title="Isomorphic Page Speed Infographic" alt="isomorphic web design page speed" onclick="window.open('https://thebhwgroup.com/sites/default/images/page-speed-1600.png', '_blank');"/></p>

<h3>Our Sample Project</h3>

<p>In this article we&#39;re going to use React, Node, and Scala to demonstrate an Isomorphic application.  All three technologies will be used on the server, and we&#39;ll use React and <a href="https://github.com/rackt/react-router">react-router</a> on the client for client-side rendering and routing.  We decided to include Scala on the server because we want to show how node can be integrated for rendering content in an existing solution, even if it&#39;s in a different language.  We&#39;ll also be demonstrating a Scala JSON API that could be easily imagined as the back-end of an existing SPA application.  We could just as easily have built the entire server solution in Node.js or many other server stacks.</p>

<h4>Scala JSON WEB API</h4>

<p>For our server we decided to use <a href="http://scalatra.org">Scalatra</a>, a micro-framework for Scala inspired by Ruby&#39;s Sinatra framework.  There are several other great Scala framework options like the MVC-based <a href="https://www.playframework.com">Play Framework</a>, but for our solution we wanted something small and lightweight that would be familiar to other developers coming from node.  Scalatra&#39;s routing system feels very similar to node.  We also wanted the Scala application to utilize the same asynchronous, event-based programming style that is one of node&#39;s main strengths.  Scalatra&#39;s asynchronous servlets provide similar functionality using <code>Futures</code> and <code>AsyncResult</code>.</p>

<h4>Scalatra Getting Started</h4>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/scalatra.png" 
      alt="Web Design with Scalatra"
      
      
       />
      
  </div>
</div>

<p>Getting started with Scalatra is very simple using this <a href="http://scalatra.org/getting-started/installation.html">guide</a>.  You only need a JDK and a few steps to be up and running quickly.  After getting installed, you can follow a second <a href="http://scalatra.org/getting-started/first-project.html">guide</a> to create your first project.  Scalatra uses SBT (simple build tool) which provides dependency management, builds, and automatic code re-loading.  You&#39;ll also want to read the instructions on setting up the ActorSystem, which manages concurrency for our asynchronous actors.  The actor we create will be responsible for making asynchronous calls to node and rendering using React.</p>

<h4>Building a Website with Scalatra</h4>

<p>After getting your template project up and running, make sure you have the following dependencies listed in your <code>build.scala</code> file:</p>
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="n">libraryDependencies</span> <span class="o">++=</span> <span class="nc">Seq</span><span class="o">(</span>
        <span class="s">&quot;org.scalatra&quot;</span> <span class="o">%%</span> <span class="s">&quot;scalatra&quot;</span> <span class="o">%</span> <span class="nc">ScalatraVersion</span><span class="o">,</span>
        <span class="s">&quot;org.scalatra&quot;</span> <span class="o">%%</span> <span class="s">&quot;scalatra-scalate&quot;</span> <span class="o">%</span> <span class="nc">ScalatraVersion</span><span class="o">,</span>
        <span class="s">&quot;org.scalatra&quot;</span> <span class="o">%%</span> <span class="s">&quot;scalatra-specs2&quot;</span> <span class="o">%</span> <span class="nc">ScalatraVersion</span> <span class="o">%</span> <span class="s">&quot;test&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.scala-lang&quot;</span> <span class="o">%</span>  <span class="s">&quot;scala-reflect&quot;</span>  <span class="o">%</span> <span class="n">scalaVersion</span><span class="o">.</span><span class="n">value</span><span class="o">,</span>
        <span class="s">&quot;org.eclipse.jetty&quot;</span> <span class="o">%</span> <span class="s">&quot;jetty-webapp&quot;</span> <span class="o">%</span> <span class="s">&quot;9.1.5.v20140505&quot;</span> <span class="o">%</span> <span class="s">&quot;container&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.eclipse.jetty&quot;</span> <span class="o">%</span> <span class="s">&quot;jetty-plus&quot;</span> <span class="o">%</span> <span class="s">&quot;9.1.5.v20140505&quot;</span> <span class="o">%</span> <span class="s">&quot;container&quot;</span><span class="o">,</span>
        <span class="s">&quot;javax.servlet&quot;</span> <span class="o">%</span> <span class="s">&quot;javax.servlet-api&quot;</span> <span class="o">%</span> <span class="s">&quot;3.1.0&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.scalikejdbc&quot;</span> <span class="o">%%</span> <span class="s">&quot;scalikejdbc&quot;</span> <span class="o">%</span> <span class="s">&quot;2.2.5&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.scalikejdbc&quot;</span> <span class="o">%%</span> <span class="s">&quot;scalikejdbc-interpolation&quot;</span> <span class="o">%</span> <span class="s">&quot;2.2.5&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.postgresql&quot;</span> <span class="o">%</span> <span class="s">&quot;postgresql&quot;</span> <span class="o">%</span> <span class="s">&quot;9.4-1200-jdbc41&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.json4s&quot;</span> <span class="o">%%</span> <span class="s">&quot;json4s-jackson&quot;</span> <span class="o">%</span> <span class="s">&quot;3.2.11&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.json4s&quot;</span> <span class="o">%%</span> <span class="s">&quot;json4s-native&quot;</span> <span class="o">%</span> <span class="s">&quot;3.2.11&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.scalatra&quot;</span> <span class="o">%%</span> <span class="s">&quot;scalatra-json&quot;</span> <span class="o">%</span> <span class="nc">ScalatraVersion</span><span class="o">,</span>
        <span class="s">&quot;net.databinder.dispatch&quot;</span> <span class="o">%%</span> <span class="s">&quot;dispatch-core&quot;</span> <span class="o">%</span> <span class="s">&quot;0.11.2&quot;</span><span class="o">,</span>
        <span class="s">&quot;com.typesafe.akka&quot;</span> <span class="o">%%</span> <span class="s">&quot;akka-actor&quot;</span> <span class="o">%</span> <span class="s">&quot;2.3.4&quot;</span><span class="o">,</span>
        <span class="s">&quot;org.scala-lang.modules&quot;</span> <span class="o">%%</span> <span class="s">&quot;scala-xml&quot;</span> <span class="o">%</span> <span class="s">&quot;1.0.3&quot;</span>
      <span class="o">)</span>
</code></pre></div>
<p>also check that your <code>plugins.sbt</code> file contains the following dependencies.</p>
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="n">addSbtPlugin</span><span class="o">(</span><span class="s">&quot;com.mojolly.scalate&quot;</span> <span class="o">%</span> <span class="s">&quot;xsbt-scalate-generator&quot;</span> <span class="o">%</span> <span class="s">&quot;0.5.0&quot;</span><span class="o">)</span>
<span class="n">addSbtPlugin</span><span class="o">(</span><span class="s">&quot;org.scalatra.sbt&quot;</span> <span class="o">%</span> <span class="s">&quot;scalatra-sbt&quot;</span> <span class="o">%</span> <span class="s">&quot;0.3.5&quot;</span><span class="o">)</span>
<span class="n">addSbtPlugin</span><span class="o">(</span><span class="s">&quot;net.virtual-void&quot;</span> <span class="o">%</span> <span class="s">&quot;sbt-dependency-graph&quot;</span> <span class="o">%</span> <span class="s">&quot;0.7.4&quot;</span><span class="o">)</span>
<span class="n">addSbtPlugin</span><span class="o">(</span><span class="s">&quot;org.scalastyle&quot;</span> <span class="o">%%</span> <span class="s">&quot;scalastyle-sbt-plugin&quot;</span> <span class="o">%</span> <span class="s">&quot;0.6.0&quot;</span><span class="o">)</span>
<span class="n">resolvers</span> <span class="o">+=</span> <span class="s">&quot;sonatype-releases&quot;</span> <span class="n">at</span> <span class="s">&quot;https://oss.sonatype.org/content/repositories/releases/&quot;</span>
</code></pre></div>
<p>Next we&#39;ll setup the ActorSystem in our <code>ScalatraBootstrap.scala</code> file below.</p>
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="c1">//other imports...</span>
<span class="k">import</span> <span class="nn">_root_.akka.actor.</span><span class="o">{</span><span class="nc">ActorSystem</span><span class="o">,</span> <span class="nc">Props</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">org.scalatra._</span>

<span class="k">class</span> <span class="nc">ScalatraBootstrap</span> <span class="k">extends</span> <span class="nc">LifeCycle</span> <span class="o">{</span>
  <span class="c1">// Get a handle to an ActorSystem and a reference to one of your actors</span>
  <span class="k">val</span> <span class="n">system</span> <span class="k">=</span> <span class="nc">ActorSystem</span><span class="o">()</span>

  <span class="k">override</span> <span class="k">def</span> <span class="n">init</span><span class="o">(</span><span class="n">context</span><span class="k">:</span> <span class="kt">ServletContext</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">context</span><span class="o">.</span><span class="n">mount</span><span class="o">(</span><span class="k">new</span> <span class="nc">DemoServlet</span><span class="o">(</span><span class="n">system</span><span class="o">),</span> <span class="s">&quot;/*&quot;</span><span class="o">)</span>
 <span class="o">}</span>

  <span class="c1">// Make sure you shut down</span>
  <span class="k">override</span> <span class="k">def</span> <span class="n">destroy</span><span class="o">(</span><span class="n">context</span><span class="k">:</span><span class="kt">ServletContext</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">system</span><span class="o">.</span><span class="n">shutdown</span><span class="o">()</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<p>Now we&#39;ll move to the main code created by the giter8 template project.  This file will be located in a subdirectory of /src/main/scala and will end with &quot;Servlet.scala&quot;.  We selected the name &quot;Demo&quot;, so our file is <code>DemoServlet.scala</code>.</p>

<p>First, make sure you have these imports:</p>
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="k">import</span> <span class="nn">org.scalatra._</span>
<span class="k">import</span> <span class="nn">scalate.ScalateSupport</span>
<span class="k">import</span> <span class="nn">org.json4s._</span>
<span class="k">import</span> <span class="nn">org.json4s.jackson.JsonMethods._</span>
<span class="k">import</span> <span class="nn">org.slf4j.</span><span class="o">{</span><span class="nc">Logger</span><span class="o">,</span> <span class="nc">LoggerFactory</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">scalikejdbc._</span>
<span class="k">import</span> <span class="nn">org.json4s.</span><span class="o">{</span><span class="nc">DefaultFormats</span><span class="o">,</span> <span class="nc">Formats</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">org.scalatra.json._</span>
<span class="k">import</span> <span class="nn">org.json4s.native.Serialization.</span><span class="o">{</span> <span class="n">read</span><span class="o">,</span> <span class="n">write</span><span class="o">,</span> <span class="n">writePretty</span> <span class="o">}</span>

<span class="k">import</span> <span class="nn">dispatch._</span><span class="o">,</span> <span class="nc">Defaults</span><span class="o">.</span><span class="k">_</span>
<span class="k">import</span> <span class="nn">scala.concurrent.</span><span class="o">{</span><span class="nc">ExecutionContext</span><span class="o">,</span> <span class="nc">Future</span><span class="o">,</span> <span class="nc">Promise</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">_root_.akka.actor.</span><span class="o">{</span><span class="nc">Actor</span><span class="o">,</span> <span class="nc">ActorRef</span><span class="o">,</span> <span class="nc">ActorSystem</span><span class="o">,</span> <span class="nc">Props</span><span class="o">}</span>
<span class="k">import</span> <span class="nn">_root_.akka.dispatch._</span>
<span class="k">import</span> <span class="nn">org.scalatra.</span><span class="o">{</span><span class="nc">ScalatraServlet</span><span class="o">,</span> <span class="nc">FutureSupport</span><span class="o">,</span> <span class="nc">AsyncResult</span><span class="o">}</span>
</code></pre></div>
<p>Next we&#39;re going to setup a case class that represents our data structure we&#39;ll use in rendering.  For our data we&#39;re going to continue our work with a datasource we created based on the <a href="https://thebhwgroup.com/blog/2014/09/bi-nodejs-couchdb-mapreduce">World Cup 2014</a>.  Our case class:</p>
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="k">case</span> <span class="k">class</span> <span class="nc">CupResult</span><span class="o">(</span><span class="n">goals_against</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="nc">_id</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">goals_for</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="nc">_rev</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">points</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">team</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>
 <span class="n">goal_diff</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">draw</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">loss</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">games</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">win</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span>
</code></pre></div>
<p>With these items in place, we can start building our sample solution.  We selected the name <code>DemoServlet</code>, so you&#39;ll need to replace with what you selected in the template step.</p>
<div class="highlight"><pre><code class="language-scala" data-lang="scala"><span class="k">class</span> <span class="nc">DemoServlet</span><span class="o">(</span><span class="n">system</span><span class="k">:</span><span class="kt">ActorSystem</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">DemoStack</span> <span class="k">with</span> <span class="nc">JacksonJsonSupport</span> <span class="k">with</span> <span class="nc">FutureSupport</span> <span class="o">{</span>
  <span class="k">protected</span> <span class="k">implicit</span> <span class="k">def</span> <span class="n">executor</span><span class="k">:</span> <span class="kt">ExecutionContext</span> <span class="o">=</span> <span class="n">system</span><span class="o">.</span><span class="n">dispatcher</span>
  <span class="k">protected</span> <span class="k">implicit</span> <span class="k">val</span> <span class="n">jsonFormats</span><span class="k">:</span> <span class="kt">Formats</span> <span class="o">=</span> <span class="nc">DefaultFormats</span>

  <span class="c1">//setup the logger</span>
  <span class="k">val</span> <span class="n">logger</span> <span class="k">=</span>  <span class="nc">LoggerFactory</span><span class="o">.</span><span class="n">getLogger</span><span class="o">(</span><span class="n">getClass</span><span class="o">)</span>

  <span class="c1">//create the postgres connection pool</span>
  <span class="nc">ConnectionPool</span><span class="o">.</span><span class="n">singleton</span><span class="o">(</span><span class="s">&quot;jdbc:postgresql://localhost:5432/worldcup&quot;</span><span class="o">,</span> <span class="s">&quot;webdemo&quot;</span><span class="o">,</span> <span class="s">&quot;test&quot;</span><span class="o">)</span>

  <span class="c1">//return list of all CupResults in the database</span>
  <span class="k">def</span> <span class="n">teams</span><span class="o">()</span><span class="k">:</span><span class="kt">List</span><span class="o">[</span><span class="kt">CupResult</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
    <span class="k">val</span> <span class="n">results</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">CupResult</span><span class="o">]</span> <span class="k">=</span> <span class="nc">DB</span> <span class="n">readOnly</span> <span class="o">{</span> <span class="k">implicit</span> <span class="n">session</span> <span class="k">=&gt;</span>
      <span class="n">sql</span><span class="s">&quot;select * from result&quot;</span>
        <span class="o">.</span><span class="n">map</span><span class="o">(</span><span class="n">rs</span> <span class="k">=&gt;</span> <span class="nc">CupResult</span><span class="o">(</span><span class="n">rs</span><span class="o">.</span><span class="n">int</span><span class="o">(</span><span class="s">&quot;goals_against&quot;</span><span class="o">),</span> <span class="n">rs</span><span class="o">.</span><span class="n">string</span><span class="o">(</span><span class="s">&quot;id&quot;</span><span class="o">),</span> <span class="n">rs</span><span class="o">.</span><span class="n">int</span><span class="o">(</span><span class="s">&quot;goals_for&quot;</span><span class="o">),</span>
          <span class="n">rs</span><span class="o">.</span><span class="n">string</span><span class="o">(</span><span class="s">&quot;rev&quot;</span><span class="o">),</span> <span class="n">rs</span><span class="o">.</span><span class="n">int</span><span class="o">(</span><span class="s">&quot;points&quot;</span><span class="o">),</span> <span class="n">rs</span><span class="o">.</span><span class="n">string</span><span class="o">(</span><span class="s">&quot;team&quot;</span><span class="o">),</span> <span class="n">rs</span><span class="o">.</span><span class="n">int</span><span class="o">(</span><span class="s">&quot;goal_diff&quot;</span><span class="o">),</span> <span class="n">rs</span><span class="o">.</span><span class="n">int</span><span class="o">(</span><span class="s">&quot;draw&quot;</span><span class="o">),</span>
          <span class="n">rs</span><span class="o">.</span><span class="n">int</span><span class="o">(</span><span class="s">&quot;loss&quot;</span><span class="o">),</span> <span class="n">rs</span><span class="o">.</span><span class="n">int</span><span class="o">(</span><span class="s">&quot;games&quot;</span><span class="o">),</span> <span class="n">rs</span><span class="o">.</span><span class="n">int</span><span class="o">(</span><span class="s">&quot;win&quot;</span><span class="o">)</span> <span class="o">)).</span><span class="n">list</span><span class="o">.</span><span class="n">apply</span><span class="o">()</span>
    <span class="o">}</span>
    <span class="n">results</span>
  <span class="o">}</span>

  <span class="k">case</span> <span class="k">class</span> <span class="nc">RenderRequest</span><span class="o">(</span><span class="n">view</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">url</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">content</span><span class="k">:</span> <span class="kt">List</span><span class="o">[</span><span class="kt">CupResult</span><span class="o">])</span>

  <span class="n">get</span><span class="o">(</span><span class="s">&quot;/standings&quot;</span><span class="o">){</span>
    <span class="n">contentType</span> <span class="k">=</span> <span class="s">&quot;text/html&quot;</span>
    <span class="k">new</span> <span class="nc">AsyncResult</span><span class="o">{</span>
      <span class="k">val</span> <span class="n">is</span> <span class="k">=</span>  <span class="nc">Future</span> <span class="o">{</span>
        <span class="c1">//build our node request</span>
        <span class="k">val</span> <span class="n">render</span> <span class="k">=</span> <span class="nc">RenderRequest</span><span class="o">(</span><span class="s">&quot;team-list&quot;</span><span class="o">,</span> <span class="s">&quot;/standings&quot;</span><span class="o">,</span> <span class="n">teams</span><span class="o">)</span>

        <span class="c1">//build json string of our RenderRequest</span>
        <span class="k">val</span> <span class="n">json</span> <span class="k">=</span> <span class="n">write</span><span class="o">(</span><span class="n">render</span><span class="o">)</span>

        <span class="c1">//dispatch the rendering async to Akka and node</span>
        <span class="nc">DispatchAkka</span><span class="o">.</span><span class="n">renderPage</span><span class="o">(</span><span class="n">json</span><span class="o">)</span>
      <span class="o">}</span>
    <span class="o">}</span>
  <span class="o">}</span>

 <span class="k">import</span> <span class="nn">_root_.akka.pattern.ask</span>
</code></pre></div>
<p>Stepping through this code, we first establish our logger and postgres connection pool.  After that, we create a method called <code>teams()</code> that returns a <code>List</code> of the case class <code>CupResult</code> we mentioned earlier.  Next we create a new case class <code>RenderRequest</code>.  We&#39;ll use a JSON serializer to convert the RenderRequest class to POST data we send to node.  RenderRequest contains the data we want to show, as well as the desired template name and the current url for routing.  Finally, we get to our Scalatra GET route <code>get(&quot;/standings&quot;)</code>.  This route asynchronously calls our node server via DispatchAkka and returns the HTML rendered by React.  There are other ways to interact with React from Scala, such as creating node as a process or using a JavaScript engine for the <a href="http://bit.ly/1fyRpAw">JVM</a>, but both have drawbacks in either data size limitations, poor JavaScript performance, or limited ECMAScript support.</p>

<p>Because we want our server to scale we decided to call node asynchronously.  In Scala, we use a <code>Future</code> that becomes available after node returns our results.  This approach to concurrency allows non-blocking, callback-based asynchronous programming for Scalatra, just like node.  The call to <code>DispatchAkka.renderPage</code> returns the result of our call to node.  With this result we can now return the final HTML to the client.</p>

<h4>Server Rendering in Node.js with React</h4>

<div class="images full-row">
  <div class="image">
    <img src="https://thebhwgroup.com/sites/default/images/nodejs-green.png" 
      alt="Web Design with NodeJS"
      
      
       />
      
  </div>
</div>

<p>Many SPA developers are already familiar with node.  In the code below we are using the <a href="https://www.npmjs.com/package/koa">koa</a> web framework along with Node v0.12 features like generators and the new asynchronous <code>yield</code> keyword.  If you haven&#39;t used these new ECMAScript 6 features, the code might be a little different than you expect.</p>

<p>The code below creates a new POST endpoint called <code>render</code>.  Any data passed to render is sent to the view requested by the client along with the data context built in the Scala code.  React renders the complete HTML and we return that from our method call.</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">AttachReact</span><span class="p">(</span><span class="nx">router</span><span class="p">){</span>
  <span class="k">return</span> <span class="k">new</span> <span class="nx">Promise</span><span class="p">((</span><span class="nx">resolve</span><span class="p">,</span><span class="nx">reject</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="k">try</span><span class="p">{</span>
      <span class="c1">//how does error surface?</span>
      <span class="nx">router</span><span class="p">.</span><span class="nx">run</span><span class="p">(</span> <span class="p">(</span><span class="nx">Handler</span><span class="p">,</span> <span class="nx">state</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
        <span class="kr">const</span> <span class="nx">body</span> <span class="o">=</span> <span class="nx">React</span><span class="p">.</span><span class="nx">renderToString</span><span class="p">(</span><span class="nx">React</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="nx">Handler</span><span class="p">,</span> <span class="kc">null</span><span class="p">));</span>
        <span class="nx">resolve</span><span class="p">(</span><span class="nx">body</span><span class="p">);</span>
      <span class="p">});</span>
    <span class="p">}</span> <span class="k">catch</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
      <span class="nx">reject</span><span class="p">(</span><span class="nx">e</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">});</span>
<span class="p">}</span>

<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="nx">router</span><span class="p">(</span><span class="nx">app</span><span class="p">))</span>
<span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;/test&#39;</span><span class="p">,</span> <span class="kd">function</span> <span class="o">*</span><span class="p">(){</span>
  <span class="c1">//provide easy route for testing to make sure node is listening</span>
  <span class="k">this</span><span class="p">.</span><span class="nx">body</span> <span class="o">=</span> <span class="s1">&#39;node running...&#39;</span><span class="p">;</span>
<span class="p">})</span>
<span class="p">.</span><span class="nx">post</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">,</span> <span class="kd">function</span> <span class="o">*</span><span class="p">(){</span>
  <span class="c1">//the endpoint called from scala</span>
  <span class="kr">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">request</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">content</span><span class="p">;</span>
  <span class="kr">const</span> <span class="nx">view</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">request</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">view</span><span class="p">;</span>
  <span class="kr">const</span> <span class="nx">url</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">request</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">url</span><span class="p">;</span>

  <span class="kr">const</span> <span class="nx">router</span> <span class="o">=</span> <span class="nx">Router</span><span class="p">.</span><span class="nx">create</span><span class="p">({</span>
    <span class="nx">location</span><span class="o">:</span> <span class="nx">url</span><span class="p">,</span>
    <span class="nx">routes</span><span class="o">:</span> <span class="nx">AppRoutes</span><span class="p">.</span><span class="nx">getRoutes</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span>
  <span class="p">});</span>

  <span class="c1">//const that = this;</span>
  <span class="k">try</span> <span class="p">{</span>
    <span class="kr">const</span> <span class="nx">body</span> <span class="o">=</span> <span class="k">yield</span> <span class="nx">AttachReact</span><span class="p">(</span><span class="nx">router</span><span class="p">);</span>
    <span class="k">yield</span> <span class="k">this</span><span class="p">.</span><span class="nx">render</span><span class="p">(</span><span class="nx">view</span><span class="p">,</span> <span class="p">{</span>
      <span class="nx">body</span><span class="o">:</span> <span class="nx">body</span><span class="p">,</span>
      <span class="nx">cacheBuster</span><span class="o">:</span> <span class="nx">uuid</span><span class="p">.</span><span class="nx">v4</span><span class="p">(),</span>
      <span class="nx">teams</span><span class="o">:</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span>
    <span class="p">});</span>
  <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;router.run exception&#39;</span><span class="p">,</span> <span class="nx">e</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">});</span>
</code></pre></div>
<h4>Isomorphic React Components</h4>

<p>Our node API method renders a template supplied by the <code>view</code> property of the JSON POST request.  The code also passes the <code>content</code> JSON property to React as state for the <code>renderToString</code> React method.  React&#39;s <code>renderToString</code> method is responsible for generating HTML using a class we created, <code>Table</code>.  <code>Table</code> is a React custom component we authored that is composed with other React classes to render our content.  Here are the contents of the <code>Table.jsx</code> file:</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kr">const</span> <span class="nx">React</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;react/addons&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">_</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;lodash&#39;</span><span class="p">);</span>
<span class="kr">const</span> <span class="nx">Row</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;./row&#39;</span><span class="p">);</span>

<span class="kr">const</span> <span class="nx">Table</span> <span class="o">=</span> <span class="nx">React</span><span class="p">.</span><span class="nx">createClass</span><span class="p">({</span>
  <span class="nx">mixins</span><span class="o">:</span> <span class="p">[</span><span class="nx">React</span><span class="p">.</span><span class="nx">addons</span><span class="p">.</span><span class="nx">PureRenderMixin</span><span class="p">],</span>

  <span class="nx">propTypes</span><span class="o">:</span> <span class="p">{</span>
    <span class="nx">initialTeams</span><span class="o">:</span> <span class="nx">React</span><span class="p">.</span><span class="nx">PropTypes</span><span class="p">.</span><span class="nx">arrayOf</span><span class="p">(</span><span class="nx">React</span><span class="p">.</span><span class="nx">PropTypes</span><span class="p">.</span><span class="nx">object</span><span class="p">).</span><span class="nx">isRequired</span>
  <span class="p">},</span>

  <span class="nx">getInitialState</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="p">{</span>
      <span class="nx">teams</span><span class="o">:</span> <span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">initialTeams</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span> <span class="nx">team</span> <span class="o">=&gt;</span> <span class="p">{</span>
        <span class="nx">team</span><span class="p">.</span><span class="nx">goalsPerGame</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">goalsPerGame</span><span class="p">(</span><span class="nx">team</span><span class="p">.</span><span class="nx">games</span><span class="p">,</span> <span class="nx">team</span><span class="p">.</span><span class="nx">goals_for</span><span class="p">);</span>
        <span class="k">return</span> <span class="nx">team</span><span class="p">;</span>
      <span class="p">})</span>
    <span class="p">};</span>
  <span class="p">},</span>

  <span class="nx">columns</span><span class="o">:</span> <span class="p">[</span>
    <span class="s1">&#39;goals_against&#39;</span><span class="p">,</span>
    <span class="s1">&#39;goals_for&#39;</span><span class="p">,</span>
    <span class="s1">&#39;points&#39;</span><span class="p">,</span>
    <span class="s1">&#39;team&#39;</span><span class="p">,</span>
    <span class="s1">&#39;goal_diff&#39;</span><span class="p">,</span>
    <span class="s1">&#39;draw&#39;</span><span class="p">,</span>
    <span class="s1">&#39;loss&#39;</span><span class="p">,</span>
    <span class="s1">&#39;games&#39;</span><span class="p">,</span>
    <span class="s1">&#39;win&#39;</span><span class="p">,</span>
    <span class="s1">&#39;gpg&#39;</span>
  <span class="p">],</span>
  <span class="nx">calcTotalGames</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nx">_</span><span class="p">.</span><span class="nx">reduce</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">teams</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">total</span><span class="p">,</span> <span class="nx">team</span><span class="p">){</span>
                      <span class="k">if</span><span class="p">(</span> <span class="nx">total</span> <span class="p">){</span>
                        <span class="k">return</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">total</span><span class="p">)</span> <span class="o">+</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">team</span><span class="p">.</span><span class="nx">games</span><span class="p">);</span>
                      <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
                        <span class="k">return</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">team</span><span class="p">.</span><span class="nx">games</span><span class="p">);</span>
                      <span class="p">}</span> <span class="p">});</span>
  <span class="p">},</span>

  <span class="nx">goalsPerGame</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">games</span><span class="p">,</span> <span class="nx">goals</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nx">goals</span> <span class="o">/</span> <span class="nx">games</span><span class="p">;</span>
  <span class="p">},</span>

  <span class="nx">handleAllClick</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="kr">const</span> <span class="nx">teamsClone</span> <span class="o">=</span> <span class="nx">_</span><span class="p">.</span><span class="nx">cloneDeep</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">teams</span><span class="p">);</span>
    <span class="nx">teamsClone</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">team</span> <span class="o">=&gt;</span> <span class="p">{</span>
      <span class="nx">team</span><span class="p">.</span><span class="nx">games</span><span class="o">++</span><span class="p">;</span>
      <span class="nx">team</span><span class="p">.</span><span class="nx">goalsPerGame</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">goalsPerGame</span><span class="p">(</span><span class="nx">team</span><span class="p">.</span><span class="nx">games</span><span class="p">,</span> <span class="nx">team</span><span class="p">.</span><span class="nx">goals_for</span><span class="p">);</span>
      <span class="k">return</span> <span class="nx">team</span><span class="p">;</span>
    <span class="p">});</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span><span class="nx">teams</span><span class="o">:</span> <span class="nx">teamsClone</span><span class="p">});</span>
  <span class="p">},</span>

  <span class="nx">render</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="kr">const</span> <span class="nx">sortedTeams</span> <span class="o">=</span> <span class="nx">_</span><span class="p">.</span><span class="nx">sortByOrder</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">teams</span><span class="p">,</span> <span class="s1">&#39;goalsPerGame&#39;</span><span class="p">,</span> <span class="p">[</span><span class="kc">false</span><span class="p">]);</span>
    <span class="k">return</span> <span class="p">(</span>
      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="nx">button</span> <span class="nx">onClick</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">handleAllClick</span><span class="p">}</span><span class="o">&gt;</span><span class="nx">All</span><span class="o">&lt;</span><span class="err">/button&gt;</span>
        <span class="o">&lt;</span><span class="nx">Link</span> <span class="nx">to</span><span class="o">=</span><span class="p">{</span><span class="err">`</span><span class="o">/</span><span class="nx">about</span><span class="err">`</span><span class="p">}</span><span class="o">&gt;</span><span class="nx">About</span><span class="o">&lt;</span><span class="err">/Link&gt;</span>

        <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">calcTotalGames</span><span class="p">()}</span><span class="o">&lt;</span><span class="err">/div&gt;</span>
        <span class="o">&lt;</span><span class="nx">table</span><span class="o">&gt;</span>
          <span class="o">&lt;</span><span class="nx">thead</span><span class="o">&gt;</span>
            <span class="o">&lt;</span><span class="nx">tr</span><span class="o">&gt;</span>
              <span class="o">&lt;</span><span class="nx">th</span><span class="o">&gt;</span><span class="nx">rank</span><span class="o">&lt;</span><span class="err">/th&gt;</span>
              <span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">columns</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">name</span> <span class="o">=&gt;</span>
                <span class="o">&lt;</span><span class="nx">th</span> <span class="nx">key</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;th-&#39;</span> <span class="o">+</span> <span class="nx">name</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">name</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/th&gt;</span>
              <span class="p">)}</span>
            <span class="o">&lt;</span><span class="err">/tr&gt;</span>
          <span class="o">&lt;</span><span class="err">/thead&gt;</span>
          <span class="o">&lt;</span><span class="nx">tbody</span><span class="o">&gt;</span>
            <span class="p">{</span><span class="nx">sortedTeams</span><span class="p">.</span><span class="nx">map</span><span class="p">((</span><span class="nx">team</span><span class="p">,</span> <span class="nx">outerIndex</span><span class="p">)</span> <span class="o">=&gt;</span>
              <span class="o">&lt;</span><span class="nx">Row</span> <span class="nx">key</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;row-&#39;</span> <span class="o">+</span> <span class="nx">outerIndex</span><span class="p">}</span>
                <span class="nx">data</span><span class="o">=</span><span class="p">{</span><span class="nx">sortedTeams</span><span class="p">[</span><span class="nx">outerIndex</span><span class="p">]}</span>
                <span class="nx">index</span><span class="o">=</span><span class="p">{</span><span class="nx">outerIndex</span><span class="p">}</span>
                <span class="nx">columns</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">columns</span><span class="p">}</span> <span class="o">/&gt;</span>
            <span class="p">)}</span>
          <span class="o">&lt;</span><span class="err">/tbody&gt;</span>
        <span class="o">&lt;</span><span class="err">/table&gt;</span>
      <span class="o">&lt;</span><span class="err">/div&gt;</span>
    <span class="p">);</span>
  <span class="p">}</span>
<span class="p">});</span>

<span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nx">Table</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nb">window</span> <span class="o">!==</span> <span class="s1">&#39;undefined&#39;</span><span class="p">)</span> <span class="p">{</span>
  <span class="nb">window</span><span class="p">.</span><span class="nx">Table</span> <span class="o">=</span> <span class="nx">Table</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p>In the above code, <code>Table</code> sets it initial state to the team list passed in from node&#39;s call to <code>React.renderToString</code>.  In an Isomorphic web application, we use a shared code base to render on the client as well.  When <code>Table</code> is used by React in server rendering, we pass the state via the call to <code>React.renderToString</code>, but if <code>Table</code> is used in the client, we pass the data in slightly differently, which we&#39;ll show in the HTML section later.  How we pass the initial state to our <code>Table</code> class doesn&#39;t matter.  React will just render whatever was given to it by the caller.  This shared code base approach is very convenient for server and client rendering.</p>

<p>Earlier we mentioned that <code>Table</code> uses composition to render with another small React class, <code>Row</code>.  Let&#39;s look at <code>row.jsx</code>:</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kr">const</span> <span class="nx">React</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;react/addons&#39;</span><span class="p">);</span>

<span class="kr">const</span> <span class="nx">Row</span> <span class="o">=</span> <span class="nx">React</span><span class="p">.</span><span class="nx">createClass</span><span class="p">({</span>
  <span class="nx">mixins</span><span class="o">:</span> <span class="p">[</span><span class="nx">React</span><span class="p">.</span><span class="nx">addons</span><span class="p">.</span><span class="nx">PureRenderMixin</span><span class="p">],</span>

  <span class="nx">propTypes</span><span class="o">:</span> <span class="p">{</span>
    <span class="nx">data</span><span class="o">:</span> <span class="nx">React</span><span class="p">.</span><span class="nx">PropTypes</span><span class="p">.</span><span class="nx">object</span><span class="p">.</span><span class="nx">isRequired</span><span class="p">,</span>
    <span class="nx">columns</span><span class="o">:</span> <span class="nx">React</span><span class="p">.</span><span class="nx">PropTypes</span><span class="p">.</span><span class="nx">arrayOf</span><span class="p">(</span><span class="nx">React</span><span class="p">.</span><span class="nx">PropTypes</span><span class="p">.</span><span class="nx">string</span><span class="p">).</span><span class="nx">isRequired</span><span class="p">,</span>
    <span class="nx">index</span><span class="o">:</span> <span class="nx">React</span><span class="p">.</span><span class="nx">PropTypes</span><span class="p">.</span><span class="nx">object</span><span class="p">.</span><span class="nx">isRequired</span>
  <span class="p">},</span>

  <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="p">(</span>
      <span class="o">&lt;</span><span class="nx">tr</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">index</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">===</span> <span class="mi">0</span> <span class="o">?</span> <span class="s1">&#39;&#39;</span> <span class="o">:</span> <span class="s1">&#39;odd&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">index</span> <span class="o">+</span> <span class="mi">1</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">goals_against</span> <span class="o">&gt;</span> <span class="mi">6</span> <span class="o">?</span> <span class="s1">&#39;red&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">goals_against</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">goals_for</span> <span class="o">&gt;</span> <span class="mi">10</span> <span class="o">?</span> <span class="s1">&#39;green&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">goals_for</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">goals_points</span> <span class="o">&gt;</span> <span class="mi">15</span> <span class="o">?</span> <span class="s1">&#39;blue&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">points</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">index</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">===</span> <span class="mi">0</span> <span class="o">?</span> <span class="s1">&#39;&#39;</span> <span class="o">:</span> <span class="s1">&#39;odd&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">team</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">goal_diff</span> <span class="o">&lt;</span> <span class="mi">0</span> <span class="o">?</span> <span class="s1">&#39;red&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">goal_diff</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">draw</span> <span class="o">&gt;</span> <span class="mi">2</span> <span class="o">?</span> <span class="s1">&#39;blue&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">draw</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">loss</span> <span class="o">&gt;</span> <span class="mi">3</span> <span class="o">?</span> <span class="s1">&#39;red&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">loss</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">games</span> <span class="o">&gt;</span> <span class="mi">10</span> <span class="o">?</span> <span class="s1">&#39;blue&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">games</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span> <span class="nx">className</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">win</span> <span class="o">&gt;</span> <span class="mi">3</span> <span class="o">?</span> <span class="s1">&#39;green&#39;</span> <span class="o">:</span> <span class="s1">&#39;&#39;</span><span class="p">}</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">win</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
        <span class="o">&lt;</span><span class="nx">td</span><span class="o">&gt;</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">goalsPerGame</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/td&gt;</span>
      <span class="o">&lt;</span><span class="err">/tr&gt;</span>
    <span class="p">);</span>
  <span class="p">}</span>
<span class="p">});</span>

<span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nx">Row</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nb">window</span> <span class="o">!==</span> <span class="s1">&#39;undefined&#39;</span><span class="p">)</span> <span class="p">{</span>
  <span class="nb">window</span><span class="p">.</span><span class="nx">Row</span> <span class="o">=</span> <span class="nx">Row</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p>In the code above, the <code>Row</code> component simply renders a single row from our team data, and <code>Table</code> maps the teams to <code>Row</code> for rendering each one.  <code>Row</code> is a much simpler React component than <code>Table</code> because it only implements the <code>render</code> method.  React applications typically use the composition pattern like this to build their view from reusable components.</p>

<h4>Isomorphic Web Design with HTML5</h4>

<p>A great way to improve page speed is to load JavaScript asynchronously.  HTML 5 added the <code>async</code> keyword for the script tag just for this purpose.  We&#39;ll make use of this tag in the HTML below to improve our page speed performance.  Our node API method renders a view using <code>React.renderToString</code>; however, in the client we use <code>React.createElement</code> along with <code>React.render</code> instead.  Consider the following template HTML we use in our application:</p>
<div class="highlight"><pre><code class="language-html" data-lang="html"><span class="cp">&lt;!DOCTYPE html&gt;</span>
<span class="nt">&lt;html&gt;</span>
<span class="nt">&lt;head&gt;</span>
  <span class="nt">&lt;title&gt;</span>Scala-NodeJS<span class="nt">&lt;/title&gt;</span>
  <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="na">type=</span><span class="s">&quot;text/css&quot;</span> <span class="na">href=</span><span class="s">&quot;css/highlight.css&quot;</span><span class="nt">&gt;</span>
<span class="nt">&lt;/head&gt;</span>
<span class="nt">&lt;body&gt;</span>
  <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;app&quot;</span><span class="nt">&gt;</span>
  <span class="err">&lt;</span>%= body %&gt;
  <span class="nt">&lt;div&gt;</span>

  <span class="nt">&lt;script </span><span class="na">id=</span><span class="s">&quot;team-content&quot;</span> <span class="na">type=</span><span class="s">&quot;application/json&quot;</span><span class="nt">&gt;</span><span class="o">&lt;%=</span> <span class="nx">teams</span> <span class="o">%&gt;</span><span class="nt">&lt;/script&gt;</span>
  <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span><span class="nt">&gt;</span>
    <span class="kd">function</span> <span class="nx">init</span><span class="p">(){</span>
      <span class="kd">var</span> <span class="nx">elem</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s2">&quot;app&quot;</span><span class="p">);</span>
      <span class="kd">var</span> <span class="nx">data</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s2">&quot;team-content&quot;</span><span class="p">).</span><span class="nx">innerHTML</span><span class="p">);</span>

      <span class="nx">Router</span><span class="p">.</span><span class="nx">attach</span><span class="p">(</span><span class="nx">elem</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="nt">&lt;/script&gt;</span>
  <span class="nt">&lt;script </span><span class="na">async</span> <span class="na">src=</span><span class="s">&quot;js/bundle.js&quot;</span> <span class="na">onload=</span><span class="s">&quot;init()&quot;</span> <span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
<span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>
</code></pre></div>
<p>On the server-side, node render&#39;s this template by replacing <code>&lt;%= body %&gt;</code> with the React rendered component.  On the client the <code>&lt;div id=&quot;app&quot;&gt;</code> element is already populated from the server-rendered content, and React simply finds the rendered HTML and re-attaches to manage the DOM.  Node also replaces the contents of our script tag <code>&lt;%= teams %&gt;</code> with a copy of the JSON model data from the server.  We send this copy of the data in the initial request so that we don&#39;t have to make an additional XHR request to load the same data later.  After React loads, it will create an observer on this data and re-render DOM elements in the <code>&lt;div&gt;</code> if the model data is changed, just like a typical SPA.</p>

<p>Also note that React, react-router, our views, components, and dependent libraries are all loaded asnychronously via the script <code>&lt;script src=&quot;js/bundle.js&quot;&gt;&lt;/script&gt;</code>.  We build the <code>bundle.js</code> using <a href="http://webpack.github.io">webpack</a> and <a href="http://gulpjs.com">gulp</a>.  After the client loads and executes this script, React starts client-side rendering to continue DOM management.  lodash and our webpack JS file should be placed in a subdirectory of <code>webapp</code> called <code>js</code>.  Scalatra will look for public static files under <code>webapp</code>.  We accomplish all of this via gulp tasks.</p>

<h4>Client DOM manipulation</h4>

<p>In our React code you probably noticed several calculated fields including <code>calcTotalGames</code> and <code>goalsPerGame</code>.  We added these fields to the <code>Table</code> component to demonstrate that they can be server rendered and continue to be maintained as React renders on the client.  In <code>Table.jsx</code> we added a <code>handleAllClick</code> method and wired it up to a button <code>onClick</code> event.  If the button is pressed in the client, React will call <code>handleAllClick</code> which alters the model, causing React&#39;s virtual DOM to change and React to re-render the row.  This button press changes the underlying state which causes React&#39;s observable pattern to notice a data difference.  React intelligently finds only the row or rows that have changed and re-renders those elements to synchronize the HTML DOM with our client state.</p>

<h4>Routing with React</h4>

<p>At this point our Isomorphic web application will deliver a SPA while ensuring SEO performance for the initial page speed and content.  Now we&#39;ll show how other routes and views on the website can be requested directly from the server.  We&#39;ll also show how navigating to other views or pages will still benefit from the client rendering advantages of a SPA.  A quick note, we&#39;re using v0.13.x of React router, but future plans for react-router v1.0 may have significant changes.  Let&#39;s discuss the two routes, <code>/standings</code> and <code>/about</code>.</p>

<p>In an Isomorphic website, we want server requests and client routes to either URL to work and render the same HTML.  We also want a user to seamlessly transition to client routing and rendering after making a request for a server rendered page.  We&#39;ll setup this scenario by adding a new route to our Scalatra app, <code>/about</code>.</p>
<div class="highlight"><pre><code class="language-scala" data-lang="scala">  <span class="n">get</span><span class="o">(</span><span class="s">&quot;/about&quot;</span><span class="o">){</span>
    <span class="n">contentType</span> <span class="k">=</span> <span class="s">&quot;text/html&quot;</span>
    <span class="k">new</span> <span class="nc">AsyncResult</span><span class="o">{</span>
      <span class="k">val</span> <span class="n">is</span> <span class="k">=</span>  <span class="nc">Future</span> <span class="o">{</span>
        <span class="c1">//build our node request</span>
        <span class="k">val</span> <span class="n">render</span> <span class="k">=</span> <span class="nc">RenderRequest</span><span class="o">(</span><span class="s">&quot;team-list&quot;</span><span class="o">,</span> <span class="s">&quot;/about&quot;</span><span class="o">,</span> <span class="n">teams</span><span class="o">)</span>

        <span class="c1">//build json string of our RenderRequest</span>
        <span class="k">val</span> <span class="n">json</span> <span class="k">=</span> <span class="n">write</span><span class="o">(</span><span class="n">render</span><span class="o">)</span>

        <span class="c1">//dispatch the rendering async to Akka and node</span>
        <span class="nc">DispatchAkka</span><span class="o">.</span><span class="n">renderPage</span><span class="o">(</span><span class="n">json</span><span class="o">)</span>
      <span class="o">}</span>
    <span class="o">}</span>
  <span class="o">}</span>
</code></pre></div>
<p>This endpoint will asynchronously request node to render our React SPA from the path <code>/about</code>.  Previously we were calling React from the url <code>/standings</code>.  Our node code correctly identifies the path difference and uses a different React component to render the view, resulting in completely different HTML than the <code>/standings</code> route we used earlier.  React knows which component to use because of the wire up in our <code>router.jsx</code> file.</p>
<div class="highlight"><pre><code class="language-javascript" data-lang="javascript">  <span class="p">...</span>
  <span class="nx">getRoutes</span><span class="p">(</span><span class="nx">data</span><span class="p">){</span>
    <span class="kr">const</span> <span class="nx">routes</span> <span class="o">=</span> <span class="p">(</span>
      <span class="o">&lt;</span><span class="nx">Route</span> <span class="nx">hander</span><span class="o">=</span><span class="p">{</span><span class="nx">App</span><span class="p">}</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="nx">DefaultRoute</span> <span class="nx">handler</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">wrapComponent</span><span class="p">(</span><span class="nx">Table</span><span class="p">,</span> <span class="p">{</span><span class="nx">initialTeams</span><span class="o">:</span> <span class="nx">data</span><span class="p">})}</span><span class="o">/&gt;</span>
        <span class="o">&lt;</span><span class="nx">NotFoundRoute</span> <span class="nx">handler</span><span class="o">=</span><span class="p">{</span><span class="nx">NotFound</span><span class="p">}</span><span class="o">/&gt;</span>
        <span class="o">&lt;</span><span class="nx">Route</span> <span class="nx">path</span><span class="o">=</span><span class="s2">&quot;standings&quot;</span> <span class="nx">handler</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">wrapComponent</span><span class="p">(</span><span class="nx">Table</span><span class="p">,</span> <span class="p">{</span><span class="nx">initialTeams</span><span class="o">:</span> <span class="nx">data</span><span class="p">})}</span><span class="o">/&gt;</span>
        <span class="o">&lt;</span><span class="nx">Route</span> <span class="nx">path</span><span class="o">=</span><span class="s2">&quot;node&quot;</span> <span class="nx">handler</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">wrapComponent</span><span class="p">(</span><span class="nx">Table</span><span class="p">,</span> <span class="p">{</span><span class="nx">initialTeams</span><span class="o">:</span> <span class="nx">data</span><span class="p">})}</span><span class="o">/&gt;</span>
        <span class="o">&lt;</span><span class="nx">Route</span> <span class="nx">path</span><span class="o">=</span><span class="s2">&quot;about&quot;</span> <span class="nx">handler</span><span class="o">=</span><span class="p">{</span><span class="nx">About</span><span class="p">}</span><span class="o">/&gt;</span>
      <span class="o">&lt;</span><span class="err">/Route&gt;</span>
    <span class="p">);</span>
    <span class="k">return</span> <span class="nx">routes</span><span class="p">;</span>
  <span class="p">},</span>
  <span class="p">...</span>
</code></pre></div>
<p>Client routing and rendering allows us to provide fast transitions between views.  Here, a user requesting <code>/about</code> is shown a small about page with a link to <code>/standings</code>.  With react-router, when the user clicks either of these links their browser doesn&#39;t make a second GET request to the server.  Instead, React router uses the client view and JSON data embedded in the page to render the standings table locally.  Try this yourself by clicking back and forth using the links to &quot;standings&quot; and &quot;about&quot;.  You will see that there are no additional server requests and the rendering is almost instant, even with a large data grid.  If you perform a hard-refresh in your browser on either of the links, forcing a server request, you will see the correct content for your current URL.  React will still attach and then route client-side for any other clicks on these links.</p>

<h2>Conclusion</h2>

<p>In this article we&#39;ve shown how to use React to render content on the server or client in an Isomorphic web application.  Isomorphic web applications are a great way to address some of the biggest SEO challenges faced by Single Page Applications.  If you are interested in learning more about this topic, please check out our <a href="https://thebhwgroup.com/blog">blog</a> for other articles on Single Page Applications.  The entire source for our article is also published on <a href="https://github.com/bhw/react-scala-isomorphic">github</a>.  Feel free to check it out and send us your thoughts and suggestions.  If you need help with your <a href="https://thebhwgroup.com/services/web-application-development-company-austin-texas">website</a> or <a href="https://thebhwgroup.com/services/mobile-app-development-company-austin-texas">mobile app development</a>, please let us know!</p>

		]]></description>

    
        <category>react</category>
    
        <category>scala</category>
    
        <category>isomorphic</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>Website Design with Clojure and Reagent</title>
        <link>https://thebhwgroup.com/blog/2015/03/website-dev-clojure-reagent</link>
		<author>Brett Burnett</author>
		<pubDate>2015-03-16T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/2015/03/website-dev-clojure-reagent</guid>
		<description><![CDATA[
		   ##Website Design and Development in Reagent

Welcome to our third article discussing <a href="https://thebhwgroup.com/services/website-design-company-austin-texas" target="_blank">website design</a> and development in [Clojure](http://clojure.org).  Clojure is an exciting Lisp language that offers full-stack web development, compiling to the JVM for server execution and to JavaScript for client side execution.  In our first article we presented [Clojure](https://thebhwgroup.com/blog/2014/08/single-page-applications-clojure-couchdb) as a server-side programming language by demonstrating a simple REST API for a Single Page Application (SPA).  In our second article we demonstrated <a href="https://thebhwgroup.com/blog/2014/09/react-angularjs-om-spa" target="_blank">Om</a>, a popular client-side scripting framework using ClojureScript and React.  Today we look at <a href="http://holmsand.github.io/reagent" target="_blank">Reagent</a>, a second philosophy to client-side web development in Clojure.

{% include full-blog-image.html src="clojure_logo.png" alt="Clojure logo" %}

##Why Reagent?

Reagent is a ClojureScript library that provides a programming and templating interface for Facebook's <a href="http://facebook.github.io/react" target="_blank">React</a> library.  Why does the Clojure community need a second client-side framework targeting React?  To answer that question, you have to consider React's history.  React's early releases required the use of a proprietary API that generated HTML and did not use traditional markup language.  In React's API, HTML DOM elements are constructed from similarly named React API functions.  React is a novel way to synchronize client-side state and the DOM, but with an already steep learning curve, Facebook decided that the API added too much additional complexity for newcomers.  In order to spur adoption, and partly remove the need to learn React's proprietary API, Facebook created a second method to integrate with React using familiar HTML templates via a JavaScript langauage extension, <a href="http://facebook.github.io/react/docs/jsx-in-depth.html" target="_blank">JSX</a>.  Today Facebook recommends React developers use JSX instead of the React API.

Om was released before Reagent and targets React's API instead of JSX.  Developers must learn the React API to program Om.  Reagent was released after Om and targets JSX instead of the React API.  This means that programming in Reagent is immediately familiar to developers who know HTML.  Learning the React API is not necessary in Reagent.

{% include full-blog-image.html src="react_logo.png" alt="React logo" %}

##Reagent and Om Compared

To demonstrate the differences between Om and Reagent we will build a small example component.  We'll create a simple component that should display the current time in the following HTML structure.

```html
<div class='time-component'>
  <h3 class='time-title'>The current time is:</h3>
  <p class='time'>{% raw %}{{24 hour time format}}{% endraw %}</p>
</div>
```


###Similarities
Both frameworks start by rendering their component into an existing DOM element specified by an ID.  A typical HTML setup for both frameworks would look like the following:

```html
<div id='simple-component'></div>
```

Om wires up our "simple-component" and renders content into this element as follows:

```clojure
(om/root simple-component app-state
    {:target (. js/document (getElementById "simple-component"))}))
```

Reagent's wire up is very similar, but slightly more compact:

```clojure
(reagent/render-component [simple-component] (.getElementById js/document "simple-component")))
```

###Where they differ
From here the two frameworks diverge, first we'll show Om's approach to implementing our "simple-component".

```clojure
(def app-state
  (atom
   {:current-time (js/Date.)}))

(defn simple-component [app owner]
  (reify
    om/IWillMount
    (will-mount [this]
                (js/setInterval #(om/update! app [:current-time] (js/Date.)) 1000))
    om/IRender
    (render [this]
            (let [time-str (-> (:current-time app) .toTimeString (clojure.string/split " ") first)]
              (dom/div #js {:className "time-component"}
                       (dom/h3 #js {:className "time-title"} "The current time is:")
                       (dom/p #js {:className "time"} time-str))))))
```

Here our Om code uses the React API Lifecycle to setup a JavaScript interval that updates our app state every second.  Om uses a single shared app state between all components which in our example is called "app-state" and contains the key "current-time".  Om manages app-state through clojure atoms which provide managed access to synchronous state.  Now the equivalent Reagent implementation:

```clojure
(defn simple-component []
  (let [current-time (atom (js/Date.))]
    (fn []
      (js/setTimeout #(reset! current-time (js/Date.)) 1000)
      (let [time-str (-> @current-time .toTimeString (clojure.string/split " ") first)]
        [:h3.time-title "The current time is:"]
        [:p.time time-str]))))
```

Our Reagent source code closely resembles a typical HTML document, which is immediately more comfortable for web developers with limited React API experience.  In our opinion the Reagent code is more concise and compact while being easier to read.  Some of the syntax complexity in Om comes from its dependence on the clojure <code>reify</code> macro to create a component which implements the React Lifecycle API.  Reagent hides this detail from the developer by handling the API interface for the user.  In our example, Reagent is able to use the <code>setTimeout</code> event instead of <code>setInterval</code> because our Reagent component returns a function for rendering instead of the actual rendered result.  Each time the component is rendered in Reagent we set a new timer.  Our Om code only wires up once in the <code>IWillMount</code> API interface so we use <code>setInterval</code> to ensure we continue to fire updates every second.

In addition to the syntax and API differences, Reagent and Om take a very different approach to state management.  Instead of following the global app state approach like Om, Reagent uses its own implementation of the atom class which re-renders dependent components based on an atom being dereferenced.  This approach allows Reagent to use local component atoms for state information that isn't shared with other components.  Our example makes use of this local state feature by declaring our current-time as an atom within the Reagent component itself.

Now that we're covered some of the differences, let's go step by step in creating a new Reagent project using Leinengen.

##Starting a Reagent Project

In this article we'll continue to use the <a href="https://thebhwgroup.com/blog/2014/09/bi-nodejs-couchdb-mapreduce" target="_blank">2014 World Cup datasource</a> shown in the prior two articles.  To start our Reagent example we first use a Leinengen template, <a href="https://github.com/reagent-project/reagent-template" target="_blank">reagent-template</a>.

```bash
lein new reagent <name> +test
```

Second, we make a few changes to the project files to include our dependencies, including <a href="https://github.com/clojure-clutch/clutch" target="_blank">clutch</a> for accessing <a href="http://couchdb.apache.org" target="_blank">CouchDB</a>.

{% include full-blog-image.html src="couchdb-logo.jpg" alt="CouchDB logo" %}

```clojure
[ring/ring-json "0.3.1"]
[com.ashafa/clutch "0.4.0"]
```

Third step, we need to change our ring middleware and include our module.  Check the  <a href="https://github.com/bhw/clojure-reagent" target="_blank">GitHub repo</a> for the complete source.  The most interesting changes happen around the construction of our ring middleware.  The sample below shows how to use the closure threading macro <code>-></code> to wrap our middleware and our JSON handlers around the request.

```clojure
(def app
  (-> (handler/api app-routes)
      (middleware/wrap-json-body)
      (middleware/wrap-json-response)))
```

Finally we start our development server and figwheel, which will start a REPL with ClojureScript and automatically compile and update our client code when we make changes to the files.

```bash
lein figwheel
```

and we get...

```bash
java.lang.NoClassDefFoundError: org/apache/http/pool/ConnPoolControl, compiling:(com/ashafa/clutch/http_client.clj:1:1)
  at clojure.lang.Compiler.load(Compiler.java:7142)
  at clojure.lang.RT.loadResourceScript(RT.java:370)
  at clojure.lang.RT.loadResourceScript(RT.java:361)
...
Caused by: java.lang.ClassNotFoundException: org.apache.http.pool.ConnPoolControl
  at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
...
```

This error indicates that we have dependency conflicts.  Leinengen gives us a handy tool to diagnose these issues, <code>deps :tree</code>.
Deps will print out a project's dependencies in a tree form, and most importantly, will show conflicts at the top of the output.

```bash
lein deps :tree
```

```bash
Possibly confusing dependencies found:
[com.ashafa/clutch "0.4.0"] -> [clj-http "0.5.5"]
 overrides
[leiningen "2.5.1"] -> [clj-http "0.9.2" :exclusions [crouton]]
...
[com.ashafa/clutch "0.4.0"] -> [clj-http "0.5.5"] -> [org.apache.httpcomponents/httpclient "4.2.1"]
 overrides
[leiningen "2.5.1"] -> [clj-http "0.9.2" :exclusions [crouton]] -> [org.apache.httpcomponents/httpmime "4.3.3" :exclusions [org.clojure/clojure]] -> [org.apache.httpcomponents/httpclient "4.3.3"]
 and
[leiningen "2.5.1"] -> [leiningen-core "2.5.1"] -> [org.apache.maven.wagon/wagon-http "2.7"] -> [org.apache.httpcomponents/httpclient "4.3.5"]
 and
[leiningen "2.5.1"] -> [clj-http "0.9.2" :exclusions [crouton]] -> [org.apache.httpcomponents/httpclient "4.3.3" :exclusions [org.clojure/clojure]]
```

##Correcting Dependencies

Resolving conflicts requires study, and in our case we can force clojure to use the latest libraries for httpclient and clj-http.  These are API compatible with the version clutch links.  To correct these dependency conflicts we need to help clojure's compiler figure out what to do.  First, we'll move clutch to the bottom of our dependency list and then we'll add these two dependency overrides.

```clojure
[com.ashafa/clutch "0.4.0"]
[org.apache.httpcomponents/httpclient "4.3.5"]
[clj-http "0.9.2" :exclusions [crouton]]
[cljs-ajax "0.3.10"]]
```

Now we're ready to start our server again with <code>lein figwheel</code>

```bash
Figwheel: Starting server at http://localhost:3449
Focusing on build ids: app
Compiling "resources/public/js/app.js" from ["src/cljs" "env/dev/cljs"]...
Successfully compiled "resources/public/js/app.js" in 12.159 seconds.
Started Figwheel autobuilder see: figwheel_server.log

Launching ClojureScript REPL for build: app
Figwheel Controls:
          (stop-autobuild)           ;; stops Figwheel autobuilder
          (start-autobuild [id ...]) ;; starts autobuilder focused on optional ids
          (switch-to-build id ...)   ;; switches autobuilder to different build
          (reset-autobuild)          ;; stops, cleans, and starts autobuilder
          (build-once [id ...])      ;; builds source once time
          (clean-build [id ..])      ;; deletes compiled cljs target files
          (add-dep [org.om/om "0.8.1"]) ;; add a dependency. very experimental
  Switch REPL build focus:
          :cljs/quit                 ;; allows you to switch REPL to another build
    Docs: (doc function-name-here)
    Exit: Control+C or :cljs/quit
 Results: Stored in vars *1, *2, *3
Prompt will show when figwheel connects to your application
To quit, type: :cljs/quit
```

##Conclusion
React is an exciting client-side framework that we use on many new projects.  Reagent makes React more accessible to Clojure developers who don't know React's API.  We feel that our Reagent code is easier to read than our Om code, especially for deeper DOM trees.  Reagent's advantages over Om stem from adopting the same strategy Facebook has taken with React's JSX interface.  Be sure to check out the entire project's source on <a href="https://github.com/bhw/clojure-reagent" target="_blank">GitHub</a>.  Our next article will be out in a few weeks and will compare the performance between SPA's built with Angular, React, JavaScript, and Clojure.

<p align="center"><em>Do you need an expert in web development? With a team of web development specialists covering a wide range of skill sets and backgrounds, <a href="https://thebhwgroup.com/services/web-application-development-company-austin-texas" target="_blank">The BHW Group</a> is prepared to help your company make the transformations needed to remain competitive in today’s high-tech marketplace.</em></p>
		]]></description>

    
        <category>clojure</category>
    
        <category>couchdb</category>
    
        <category>json</category>
    
        <category>rest</category>
    
        <category>reagent</category>
    
    
        <category>Development</category>
    

	  </item>
    
  </channel>
</rss>
