<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>react &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/react/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Mon, 07 Oct 2019 14:40:51 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>react &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>React Redux Thunk vs Elm</title>
		<link>https://jessewarden.com/2019/10/react-redux-thunk-vs-elm.html</link>
					<comments>https://jessewarden.com/2019/10/react-redux-thunk-vs-elm.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sat, 05 Oct 2019 19:20:44 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[elm]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[react]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5848</guid>

					<description><![CDATA[Introduction It’s a bit easier to learn Elm if you compare it to things you know. If you know React and Redux, then comparing them can help a lot to understand Elm concepts. I’ve built the same application in React Redux Thunk and Elm so we can compare them together. The end result is a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>It’s a bit easier to learn Elm if you compare it to things you know. If you know React and Redux, then comparing them can help a lot to understand Elm concepts. I’ve built the same application in React Redux Thunk and Elm so we can compare them together. The end result is a table of things you can paginate through. Comparing these 2 applications is apples to apples. They’re identical to the end user. Yet the technologies behind them are apples to oranges. Seeing those deviations using familiar tech in the same application can help your understanding.</p>



<span id="more-5848"></span>



<p>Below, I&#8217;ve linked to both applications code bases which you can download and run locally if you wish.</p>



<p><a href="https://github.com/JesterXL/react-vs-elm-react-redux-thunk">Company Dashboard Code &#8211; React Redux Thunk</a></p>



<p><a href="https://github.com/JesterXL/react-vs-elm-elm">Company Dashboard Code &#8211; Elm</a></p>



<h2 class="wp-block-heading">What is React, Redux, Thunk, and Elm?</h2>



<p><a href="https://reactjs.org/">React</a> is a JavaScript library that allows you to ensure your HTML and CSS are in sync with your data. You use this to build single page web applications.</p>



<p><a href="https://redux.js.org/">Redux</a> is a library that allows you have a single variable for your data model. This ensures your applications are predictable and testable. It is the core of the Elm architecture and is often used in React.</p>



<p><a href="https://github.com/reduxjs/redux-thunk">Thunk</a> is a library that allows your Redux actions to be asynchronous.</p>



<p><a href="https://elm-lang.org/">Elm</a> is a functional programming language, compiler, repl, package manager, and a set of libraries to build single page applications. You write in Elm and it compiles to <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a>.</p>



<h2 class="wp-block-heading">Building and Compiling React</h2>



<p>You build React applications using <a href="https://nodejs.org/en/">Node.js</a>. Using a package manager like <a href="https://yarnpkg.com/lang/en/">Yarn</a> or <a href="https://www.npmjs.com/">npm</a> to install libraries, and run commands to test and build your application for production. Yarn and Node utilize npm, the Node Package Manager, to install libraries and interface with Node. Yarn is used mainly because it has advanced features that npm doesn&#8217;t have, and it can yield more deterministic installs and builds compared to npm. Front-end applications tend to have more libraries than back-end Node API ones. Yarn is used more often in React given it&#8217;s front-end. The source of truth is usually a <code>package.json</code>, a JSON file that contains all the libraries to be installed and commands needed to test and build the application. This holds true whether the application is regular JavaScript, using advanced <a href="https://www.freecodecamp.org/news/write-less-do-more-with-javascript-es6-5fd4a8e50ee2/">ES6</a> features, using advanced compilation tools like <a href="https://babeljs.io/">Babel</a> and <a href="https://webpack.js.org/">Webpack</a>, and/or utilizing typed languages like as <a href="https://flow.org/">Flow</a> and <a href="http://www.typescriptlang.org/">TypeScript</a>.</p>



<p>The easiest way to build them at the time of this writing is using <a href="https://github.com/facebook/create-react-app">create-react-app</a>, which abstracts most of the compilation and build toolchain away into simple commands with updates being usually as simple as updating the <code>react-scripts</code> library.</p>



<p>Like Elm, React can compile to simple components embedded in other web applications. It can also compile too large, single page applications.</p>



<h2 class="wp-block-heading">Building and Compiling Elm</h2>



<p>For simple applications, Elm the language is compiled to JavaScript and HTML through the Elm compiler via <code>elm make</code>. For more advanced applications, the compiler will output just JavaScript that you embed in your HTML. Libraries are installed through <code>elm install</code> and written in <code>elm.json</code>. While there is a local web server called <code>elm reactor</code>, it lacks many basic features such as auto-refresh that many other JavaScript tools have. Use elm-live instead.</p>



<p>Like React, you&#8217;ll use Node, npm, and/or yarn to various degrees of complexity.  Like React, Elm can compile to simple components embedded into other web applications. Elm can also be used to build large, single page applications. The common ways to build at the time of this writing is create-elm-app which isn&#8217;t very friendly behind corporate proxies, and the simpler <a href="https://github.com/wking-io/elm-live">elm-live</a>. If you&#8217;re not on a corporate network, <a href="https://github.com/halfzebra/create-elm-app">create-elm-app</a> is also an option.</p>



<p>Although Elm is fully featured, it&#8217;s still missing features native to JavaScript. As such you&#8217;ll sometimes interface with JavaScript. At the time of this writing for Elm version 0.19.0, this includes binary file upload, and application storage to name just two. This ensures you can benefit from Elm&#8217;s features, but not have to wait on them or the open source community to build Elm versions of those features.</p>



<h2 class="wp-block-heading">HTML in React</h2>



<p><a href="https://en.wikipedia.org/wiki/HTML">HTML</a> in React is rendered by React via <a href="https://reactjs.org/docs/introducing-jsx.html">JSX</a>. They handle all the efficient ways of updating it, the cross-browser challenges, etc. All you do is provide a function or class with a render function that returns this JSX.</p>



<p><code>const Message = () =&gt; (&lt;div&gt;Sup&lt;/div&gt;)</code></p>



<p>Then you can use this &#8220;component&#8221; like a normal HTML tag in your other React JSX:</p>



<p><code>&lt;Message /&gt;</code></p>



<p>React became popular with functional programmers because it was basically a pure function for the DOM. A pure function is a function that always outputs the same thing if you give it the same arguments with no side effects. You give the <code>Message</code> component above an Object, and React will render the same DOM each time. This input in React is called &#8220;props&#8221; or properties.</p>



<p><code>const Message = props =&gt; (&lt;div&gt;Sup {props.name}&lt;/div&gt;</code></p>



<p>Whenever that <code>props.name</code> value changes, so too will the HTML React renders. You can embed JavaScript or just values like the above using the squiggle braces ({}). There are a variety of rules that make JSX not exactly like HTML. There are a host of them, but examples include event objects are a custom copy to prevent certain bugs, and using <code>onClick</code> instead of <code>onclick</code> for events. That said, React has done a great job to make it feel and work like you&#8217;d expect HTML to work.</p>



<h2 class="wp-block-heading">HTML in Elm</h2>



<p>Everything in Elm is a function. HTML is no different. Each HTML element has a corresponding function name. All HTML elements typically have attributes and contents. Below, the <code>div</code> tag has a style attribute and text contents:</p>



<p><code>&lt;div style="color: red;"&gt;Sup&lt;/div&gt;</code></p>



<p>In Elm, you&#8217;d import and use the <code>div</code>, <code>style</code>, and <code>text</code> functions to accomplish the same thing:</p>



<p><code>div [ style "color" "red"] [ text "Sup" ]</code></p>



<p>Elm functions do not use commas, and parenthesis are optional in most cases. Above the <code>div</code> function takes 2 list arguments, the style function 2 string arguments, and text 1 string. Rewritten in JavaScript that&#8217;d be:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">div</span>(<span class="hljs-selector-attr">&#91;style(<span class="hljs-string">'color'</span>, <span class="hljs-string">'red'</span>)]</span>, <span class="hljs-selector-attr">&#91;text(<span class="hljs-string">'Sup'</span>)]</span>)</code></span></pre>


<h2 class="wp-block-heading">Working With CSS in React</h2>



<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS">Cascading Style Sheets</a> have a lot of different ways of working in React depending on what you&#8217;re building, and the team&#8217;s style. Component based styles have risen in popularity in React. The first reason for this is it&#8217;s easier for modern tools to &#8220;only compile what you use&#8221;; if you don&#8217;t use the component, it won&#8217;t compile the CSS in. Larger websites that have accrued many shared styles from many teams over years have this issue. Since the tools aren&#8217;t very good to ensure modifying styles doesn&#8217;t break something else unintentionally, teams end up adding new styles of their own to prevent breakage which just adds to the file size and speed slow down despite not being inline. The second reason for this is co-location. The styles that handle the component are right next to it; you don&#8217;t have to hunt around various css, sass, or externalized html template files to &#8220;piece together&#8221; how a component is supposed to look.</p>



<p>React supports normal <code>className</code> attributes to emulate how the <code>class</code> attribute works. You can also use <code>style</code> create CSS through JavaScript Objects. This is popularized by the &#8220;CSS-in-JS&#8221; movement, and keeps your styles co-located to the components they are affecting. There are libraries that take this concept to the nth degree such as <a href="https://emotion.sh/docs/introduction">Emotion</a>. Teams will either standardize on one approach depending on team make up, and/or use a multitude depending upon what they&#8217;re building and interfacing with. Beyond the <code>className</code> and <code>style</code> attributes for JSX, React&#8217;s version of HTML, React doesn&#8217;t prescribe how you handle CSS.</p>



<p>Styling with <code>className</code>:<br><code>&lt;div className="textColor"&gt;Sup&lt;/div&gt;</code></p>



<p>Styling with <code>style</code>:<br><code><code><code><br>const myStyles = {<br>  color: 'red'<br>}<br>&lt;div style={myStyles}&gt;Sup&lt;/div&gt;</code></code></code></p>



<h2 class="wp-block-heading">Working with CSS in Elm</h2>



<p>Elm, like React, doesn&#8217;t prescribe a way how you handle CSS. Elm&#8217;s version of HTML is functions. There is a function for each html element. If you&#8217;re adding styles to a <code>div [] []</code>, then you&#8217;d go <code>div [ style "color" "red"] []</code>. If you want to use a css class, you&#8217;d go <code>div [ class "textColor" ] []</code>.</p>



<p>The only modification is if you wish to have stronger compiler help with your CSS, you can use the <a href="https://github.com/rtfeldman/elm-css">elm-css</a> library. The normal Elm style function doesn&#8217;t give you much help from the compiler given both arguments are strings. The elm-css library on the other hand ensures both types and argument order which really makes the most of the Elm compiler.</p>



<h2 class="wp-block-heading">Coding in React</h2>



<p>In React, you typically write in JavaScript. It&#8217;s a dynamic, interpreted language that is native in all browsers. Dynamic means you can change a variable that is a number to string or any type you want. Interpreted means you can write some code, put in the browser, and it&#8217;ll run. You do not need to compile yourself. The browser handles converting that to machine code that it can run quickly. You can debug the code, in the browser, using both logs and breakpoints which stop the code from running and allow you to step through each part line by line.</p>



<p>This also means that most styles of programming are supported. This includes Imperative, Object Oriented, and Functional. Imperative being many lines of code in a file that run from top to bottom in a procedural way. Object Oriented mean classes that encapsulate state, message passing, and a variety of design patterns.  Functional meaning pure functions.</p>



<p>React allows both CSS and HTML to be written in JavaScript. This means that everything that makes up the visual elements on the screen can be put right next to each other, giving you a clearer picture of how each visual thing works. Sometimes. </p>



<p>The pros of a dynamic language are speed of development. You can quickly play with new ideas using only a little code. You don&#8217;t need any tools to make it work beyond a web browser. If you need a server, you can write the same language, JavaScript, to make Node do this for you.</p>



<h3 class="wp-block-heading">Prop Types</h3>



<p>The cons of a dynamic language is you have to run it to know if it works. While running can be fast, sometimes you have to click through the UI to trigger some part of the code, and that process isn&#8217;t that fast, or is tediously manual. Many tools can automate these kind of checks. For UI development in the browser, this is often verifying the components attributes (their inputs) and their events (change handlers).</p>



<p><code>&lt;CrayButton label={datText} onGo={clickHandler} /&gt;</code></p>



<p>However, you won&#8217;t know if <code>datText</code> is actually a String, nor if <code>clickHandler</code> is a Function with proper scoping and no negative down stream effects till you actually test it. To help a bit with these problems, React has <code>propTypes</code> which has a bit of runtime type checking. You still have to run the code, and it only works in development mode, BUT it quickly aborts the code with correct errors vs. errors which may not be clear what went wrong.</p>


<pre class="wp-block-code"><span><code class="hljs">CrayButton.propTypes = {
  label: PropTypes.string,
  onGo: PropTypes.func
}</code></span></pre>


<h3 class="wp-block-heading">Flow or TypeScript</h3>



<p>Computers are much better than humans at finding, storing, and quickly accessing large amounts of numbers. For code, there are many different paths that could happen, and compilers are good at quickly verifying if your code is going to work or not in milliseconds to microseconds. One of the ways they do this is through types. You write in a different language entirely, then the compiler will convert it to JavaScript. Like the <code>propTypes</code> above, except the code won&#8217;t actually compile if it finds errors. Once you fix all the errors, it&#8217;ll then compile. The theory is in the little time it takes you to add types to the code, the compiler can find errors in microseconds to minutes. These milliseconds/minutes are supposed to be much shorter than the time it takes you to track down bugs.</p>



<p><a href="https://flow.org/">Flow</a> and <a href="http://www.typescriptlang.org/">TypeScript</a> both offer really nice types with the ability to integrate with existing JavaScript and libraries. If a library was coding in JavaScript, many will offer TypeScript definitions which give the public API functions it exposes types. This allows TypeScript to offer type checking on it even though the library is JavaScript and has no types. For large codebases that already exist, including libraries, it&#8217;s much easier to create a definition file.</p>



<p>The create-react-app generator offers a TypeScript option, again abstracting away all the work to setup and maintain the compiler. The TypeScript/Flow flexibility, however, means that you have less guarantees that when your code actually compiles, it&#8217;ll work. Flow and TypeScript both compile to JavaScript, and have no runtime type checking.</p>



<h2 class="wp-block-heading">Coding in Elm</h2>



<p>In Elm, you write in the Elm language. It is functional and strongly typed. Functional means pure functions with no side effects. In fact, you cannot create side effects at all in Elm. The Elm framework handles all side effects for you. Everything from creating HTML to REST calls are simply pure functions. The types use Haskell style Hindly-Milner types. You put the function&#8217;s input(s) and output up top, and that&#8217;s all the compiler needs. This as opposed to TypeScript and ReasonML for example, where you put next to the variables at the end of the function. The function below is a simple add function, taking in 2 numbers, and returning whatever they are added together.</p>


<pre class="wp-block-code"><span><code class="hljs">add : Int -&gt; Int -&gt; Int
add first second = first + second</code></span></pre>


<p>That said, the compiler is pretty smart, so you can omit them and it&#8217;ll &#8220;know what you meant&#8221;.</p>


<pre class="wp-block-code"><span><code class="hljs">add first second = first + second</code></span></pre>


<p>In JavaScript, that&#8217;d be:</p>



<p><code>add = (first, second) =&gt; first + second</code></p>



<p>&#8230; sort of. Since all Elm functions are curried by default, a more accurate JavaScript representation would be:</p>



<p><code>add = first =&gt; second =&gt; first + second</code></p>



<p>Unlike Flow or TypeScript, Elm ensures when it compiles, you will not get any null pointer exceptions. There are only 2 ways to break this guarantee. The first is integrating with JavaScript through ports and you aren&#8217;t careful, or you are, but the JavaScript is just obnoxious. The second way is in development mode sending large amounts of text into the <code>Debug.log</code> function, using all of the browser&#8217;s memory.</p>



<p>As a functional language, there are no exceptions. This means all <code>Error</code>&#8216;s are return values. More on error handling below.</p>



<p>In React, it&#8217;s not uncommon to see functions, classes, strings, numbers, modules, and images all in the same code base. In Elm, everything is a function or a type.</p>



<h2 class="wp-block-heading">Side Effects in JavaScript</h2>



<p>In JavaScript, you have control over some side effects. You can even create them yourself. This includes logging to the console, creating HTTP requests, reading from various storage locations such as files, listening for push requests on web sockets, various events from user interactions such as mouse clicks, and when the browser URL changes.</p>



<p>The ways these work varies from return values, callbacks, event handlers, to Promises. Some of these have built-in error handling and some do not.</p>



<p>To parse JSON from an outside source, it does a return value. If it fails, it&#8217;ll throw an exception you catch via <code>try/catch</code>.<br><code>result = JSON.parse('{"sup": "yo" }')</code> </p>



<p>To listen to mouse events in React, it&#8217;s common to use inline callbacks:</p>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> console.log("Clicked, sucka!")}&gt;Sup<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></code></span></pre>


<p>However, you can do it the event based way as well. We use a class method below so it can be cleaned up later.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">theButton.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-keyword">this</span>.clickHandler)</code></span></pre>


<p>Many newer API&#8217;s offer Promises, and Promises have built-in try/catch. Here&#8217;s how to make an HTTP GET request using <code>fetch</code> which returns a Promise:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">fetch(someURL)
.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
.then(<span class="hljs-function"><span class="hljs-params">json</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"json is:"</span>, json))
.catch(<span class="hljs-built_in">console</span>.log)</code></span></pre>


<p>When unit testing, you&#8217;ll typically either mock the concretes using something like <a href="https://sinonjs.org/">Sinon</a> or <a href="https://github.com/testdouble/testdouble.js/">Test Double</a> to make the code more predictable. If you&#8217;re using functional style, you&#8217;ll pass in the module/class as one of the function parameters, and then a stub in your unit tests.</p>



<h2 class="wp-block-heading">Side Effects in Elm</h2>



<p>All side effects in Elm, with the exception of <code>Debug.log</code> in development, and JavaScript ports, are handled by Elm itself. You cannot create side effects in Elm. You merely create functions that return data. The Elm Architecture handles the actual side effects, allowing all of your code to be pure. We&#8217;ll talk more about how you get actual things done in the Elm Architecture section below. For now, just know that you can make the Elm Architecture create and handle side effects via one of the 3:</p>



<ol class="wp-block-list"><li>Messages (think onClick + Redux Action Creator)</li><li>Commands (think Redux Action Creator)</li><li>Subscriptions (think Thunks or Sagas triggered from <code>window.onlocationchange</code> or web sockets)</li></ol>



<h2 class="wp-block-heading">Closures in React</h2>



<p>Closures are a way for functions inside of functions retain scope and values. It&#8217;s mainly used for OOP developers to have hack around <code>this</code> changing.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someMethod</span>(<span class="hljs-params">input</span>) </span>{
  <span class="hljs-keyword">const</span> me = <span class="hljs-keyword">this</span>;
  $(<span class="hljs-string">'.thing'</span>).click(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> me.otherMethod())
}</code></span></pre>


<p>It also allows JavaScript developers to have more predictable state, especially with asynchronous code:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">let</span> state = <span class="hljs-string">'ready'</span>
<span class="hljs-keyword">const</span> loadData = <span class="hljs-function"><span class="hljs-params">url</span> =&gt;</span> {
  state = <span class="hljs-string">'loading'</span>
  fetch(url)
  .then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
    state = <span class="hljs-string">'done'</span>
  })
  .catch(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
    state = <span class="hljs-string">'error'</span>
  })</code></span></pre>


<p>They also can play an important role of reducing how many parameters your functions need as the inner functions can just access the outer/wrapping function values. They play pivotal role in how curried functions work in JavaScript. For asynchronous code such as nested callbacks and Promises, they can significantly help in reducing the code size, and keeping track of asynchronous processes in 1 place.</p>



<p>For React, they&#8217;re the primary way you utilize Hooks.</p>



<h2 class="wp-block-heading">Closures in Elm</h2>



<p>Closures in Elm work differently. While you can nest functions, and have inner functions access outer function parameters:</p>


<pre class="wp-block-code"><span><code class="hljs">-- note we're referencing model.label inside the button function
view model =
  div &#91;] &#91;
    button model.label
  ]</code></span></pre>


<p>&#8230;they do not propagate &#8220;later&#8221;. Since there is no async in Elm, you cannot &#8220;keep things around&#8221; long after a function has finished executing like you&#8217;d normally do in JavaScript with the exception of partial applications.</p>



<p>For example, if you&#8217;re doing many of the same HTTP calls on the client, they could come back in different orders. Often you&#8217;ll give each a different id so you can tell which call was which, and in what order it was sent. This allows you to do different versions of queues and concurrency. If you&#8217;re refreshing a table over and over, you may make 5 calls one after the other, but you really only care about the last one.  In a chat for example, you actually care about FIFO, first in first out. You want to ensure you&#8217;ve handled all the calls in order to the best of your ability, and want to ensure the chat messages show in order assuming you&#8217;re lacking a timestamp to order them. </p>



<p>That control of state in JavaScript allows you to add a unique identifier using closures. Here is how you create a correlation ID in some JavaScript <code>fetch</code> code:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> load = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> correlationID = uuidv4()
  <span class="hljs-keyword">return</span> fetch(url, {<span class="hljs-attr">headers</span>: {<span class="hljs-string">'x-correlation-id'</span>: correlationID })
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
  .then(<span class="hljs-function"><span class="hljs-params">json</span> =&gt;</span> (&#91; json, correlationID ]) )
}</code></span></pre>


<p>In Elm, you could reference the <code>correlationID</code> above in the request, but NOT in the response like you can in JavaScript. Since the actual side effect is handled by the framework, you&#8217;d have to user their built in <a href="https://package.elm-lang.org/packages/elm/http/latest/Http#request">trackers</a>. The Elm API > v0.19.0 at the time of this writing is still figuring out how to handling concurrency for a variety of things. </p>



<h2 class="wp-block-heading">Errors in React</h2>



<p>Like <a href="https://dart.dev/">Dart</a> and <a href="https://angularjs.org/">Angular</a> before it, React really has done some interesting things with Error handling. The first was <a href="https://reactjs.org/docs/error-boundaries.html">error boundaries</a>. Anyone who&#8217;s built UI&#8217;s knows that handling errors when drawing things is rough. Doing it in an async way is even harder since it&#8217;s hard to track where and when it may have occurred. Building errors into the components was a great first step in ensuring a single error didn&#8217;t bring down a whole application. Using throw in <a href="https://github.com/acdlite/react-fiber-architecture">Fiber</a>, their architecture that builds their own call stack, they can create <a href="https://overreacted.io/algebraic-effects-for-the-rest-of-us/">Algebraic Effects</a>. This means errors can be resumed safely from anywhere. </p>



<p>That said, errors in React are basically errors in JavaScript. They have tons of problems.</p>



<p>First, they aren&#8217;t pure. Pure functions have no side effects. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Errors</a>, even in the browser, cause side effects. They can put code currently, or later, into an unknown state. This could be from synchronous UI code, asynchronous <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">WebWorkers</a>, or some 3rd party library you&#8217;re not even sure is involved. If your web application has monitoring such as <a href="https://www.catchpoint.com/">Catchpoint</a>, you can get a text message at 3am because of an uncaught null pointer. Thus, they&#8217;re hard to predict and make your code flaky.</p>



<p>Second, JavaScript doesn&#8217;t really have good error handling facilities. They make it really easy to hurt yourself, the code, and the browser (or Node.js). Some languages languages such as Java have <code>throwable</code>. If a function has that, the compiler forces you to catch it. JavaScript has no such facilities, and is interpreted so you don&#8217;t know about errors until you run the code, see them, and get screwed over by them. Adding try/catch everywhere is not fun to write, nor read, and slows your code down. The asynchronous ones are a bit better in that <code>catch</code> on Promises only has to be written once, but with the popularity of <code>async</code> <code>await</code> syntax, people forego even writing those. They let explosions happen there uncaught as well. The <code>window.onerror</code> is a strange method with various browser support intricacies that can sometimes affect how bad the crash is based on what you return. This is still great to have it, but it has the same thing in common with <code>try</code> <code>catch</code> and the <code>catch</code> on a Promise: you can screw those up, and cause another error with no language/compiler support.</p>



<p>Third, the stack traces aren&#8217;t always accurate to what&#8217;s going on. They&#8217;ve greatly improved over the years since I abandoned Flash Player for JavaScript. Still, errors don&#8217;t always originate from the exact line of code that caused the error, or do but say something inaccurate to what&#8217;s actually causing the problem.</p>



<h2 class="wp-block-heading">Errors in Elm</h2>



<p>Elm doesn&#8217;t throw errors, that&#8217;s one of the draws of using it. Instead, if a function can fail, you return a <a href="https://package.elm-lang.org/packages/elm/core/latest/Result">Result</a>. The compiler will ensure you&#8217;re handling it correctly. There are a few types that you can chain together like Promises such as <a href="https://package.elm-lang.org/packages/elm/core/latest/Maybe">Maybe</a> and Result. If they fail, you handle the error in 1 place. These errors are return values and do not negatively affect the rest of your program.</p>



<p>If you&#8217;re in debug mode and send too much text, you can use all of the browser&#8217;s available memory and crash the program that way. Elm will not compile for production builds unless logs are removed.</p>



<p>If you&#8217;re using 3rd party JavaScript libraries on the page, or using ports with volatile JavaScript, they will also crash your program.</p>



<h2 class="wp-block-heading">Redux in React</h2>



<p><a href="https://redux.js.org/">Redux</a> is a framework inspired by Elm to help bring predictability to larger React applications. At some point when you outgrow <a href="https://reactjs.org/docs/context.html">Context</a>, or just want the predictability that Functional Programming can bring, you reach for Redux. It ensures only 1 variable is in your entire application, and that 1 variable is all the data your application needs. You can use the <a href="https://github.com/zalmoxisus/redux-devtools-extension">Redux Dev tools</a> to see your data change over time and clearly see the state changes, the order, and how they affect your UI. Since React components are pure functions that take in props and render DOM, Redux scales this concept for for the data.</p>



<p>Below is a crash course in Redux. You are welcome to skip it. I include it here for those who do not know Redux very well, nor why you even use it. Knowing how Redux works helps you understand how Elm works since they&#8217;re based on the same ideas.</p>



<h3 class="wp-block-heading">Reducers</h3>



<p>In Redux you have <code>store</code>; this is the main variable that stores your data. You get it via <code>store.getState()</code> and change it via <code>store.dispatch({action})</code>. The dispatch will call you reducers, or a function that takes in the state and the action. If you know the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">Array.reduce</a> function, it&#8217;s the same thing. It&#8217;s assumed that your reducers do not mutate data, and simply return a copy of the store with whatever changes you need. Updating a person&#8217;s name for example would go like this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> firstNameReducer = <span class="hljs-function">(<span class="hljs-params">person, action</span>) =&gt;</span> ({ ...person, <span class="hljs-attr">firstName</span>: action.firstName })</code></span></pre>


<p>If I pass in <code>firstNameReducer( { firstName: 'cow' }, { type: 'updateFirstName', firstName: 'Albus' } )</code>, then it&#8217;ll return a brand new Object <code>{ firstName: 'Albus' }</code>. This is important because it means the code returns immutable data, doesn&#8217;t mutate anything, and is easily testable. Thus, predictable. When you start building an application full of those reducer functions, your application becomes more predictable.</p>



<p>If you&#8217;re from an <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a> background, you&#8217;re probably wondering why in the heck you can&#8217;t just go <code>UserModel.getInstance().firstName = 'Albus'</code> or even <code>UserController.getInstance().setFirstName('Albus')</code>. Or even just modifying on the variable in general. Remember, Redux uses pure functions. Pure functions do not mutate or &#8220;change&#8221; data. If you use immutable data, this ensures you&#8217;re following pure function rules. If you mutate things, then it&#8217;s not predictable who changes things, and where. If you use pure functions in Redux, the only mutation occurs in the store. You can predict which actions, in order, change your data and can visualize it using browser tools or simple logs. Yes, you can set a breakpoint in Java or JavaScript, and follow all the getter/setters for one code path, but not all. This is where you get &#8220;who&#8217;s changing my data, where, and when&#8221;. Redux has the same challenges, but it&#8217;s super clear &#8220;who&#8221; is doing it, and &#8220;how&#8221;. Since each change is immutable, there is no weird references going on.</p>



<h3 class="wp-block-heading">Store</h3>



<p>If data is immutable, then how do you change it? VERY carefully. Redux does this via reducer functions.</p>



<p>We know how to write pure functions that return immutable data, but nothing in the real world is immutable. Someone, somewhere has to hold the data we get back from the server, the changes the user makes on the UI, etc. That 1 <code>var</code> is the Store.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> store = createStore(firstNameReducer, { <span class="hljs-attr">firstName</span>: <span class="hljs-string">'???'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Warden'</span> })</code></span></pre>


<p>This store holds your data. Notice we&#8217;ve put our reducer function for it as the 1st parameter. </p>



<p>You get it out via <code>getState</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> person = store.getState() <span class="hljs-comment">// { firstName: '???', lastName: 'Warden' }</span></code></span></pre>


<p>To change the data, we call the dispatch method and pass in an Object:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">store</span><span class="hljs-selector-class">.dispatch</span>({ <span class="hljs-attribute">type</span>: <span class="hljs-string">'updateFirstName'</span>, firstName: <span class="hljs-string">'Jesse'</span> })</code></span></pre>


<p>Now when we get our data out, it&#8217;ll be changed:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> updated = store.getState() <span class="hljs-comment">// { firstName: 'Jesse', lastName: 'Warden' }</span></code></span></pre>


<h3 class="wp-block-heading">Action Creator</h3>



<p>The Object you pass as the 1st and only parameter to <code>dispatch</code> is called the &#8220;Action&#8221;. However, purist Functional people get mad creating random Objects, so they create a pure function. Those are suddenly called &#8220;Action Creators&#8221;:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">firstNameAction = <span class="hljs-function"><span class="hljs-params">firstName</span> =&gt;</span> ({ <span class="hljs-attr">type</span>: <span class="hljs-string">'updateFirstName'</span>, firstName })</code></span></pre>


<p>An Action Creator is a function that return an Object. It&#8217;s assumed that Object, at a minimum, has a type property. You&#8217;ll use that <code>type</code> in your reducer function to know what data you want to change.</p>



<h3 class="wp-block-heading">Many Types</h3>



<p>As your application grows, you&#8217;ll probably need to change many aspects of your data model. For our person, we want to change the last name as well. So we create another reducer for changing the last name, but using a pure function. This means a copy of the data is returned vs. mutating it:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> lastNameReducer = <span class="hljs-function">(<span class="hljs-params">person, action</span>) =&gt;</span> ({ ...person, <span class="hljs-attr">lastName</span>: action.lastName })</code></span></pre>


<p>To trigger it, we need another action creator for updating lastName:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">lastNameAction = <span class="hljs-function"><span class="hljs-params">lastName</span> =&gt;</span> ({ <span class="hljs-attr">type</span>: <span class="hljs-string">'updateLastName'</span>, lastName })</code></span></pre>


<p>When we created our store above, we put the <code>firstNameReducer</code> with our store to handle all dispatches. Now we need both reducers, and each needs to run based on the <code>type</code> of Action Creator. Let&#8217;s create a new one that uses a switch statement.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> personReducer = <span class="hljs-function">(<span class="hljs-params">person, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'updateFirstName'</span>:
      <span class="hljs-keyword">return</span> firstNameReducer(person, action)
    <span class="hljs-keyword">case</span> <span class="hljs-string">'updateLastName'</span>:
      <span class="hljs-keyword">return</span> lastNameReducer(person, action)
  }
}</code></span></pre>


<p>In a unit test, if we call <code>personReducer</code> with <code>{}, { type: 'updateFirstName', firstName: 'Joe' }</code> then we&#8217;ll get back <code>{ firstName: 'Joe' }</code>. If we call it with <code>{}, { type: 'updateLastName', lastName: 'Hall' }</code>, then we&#8217;ll get back <code>{ lastName: 'Hall' }</code>. </p>



<p>To call it in your application, or even in a unit test, you&#8217;d go <code>store.dispatch(lastNameAction('Warden'))</code> to update the <code>lastName</code> to &#8220;Warden&#8221;.</p>



<p>As that switch statement grows, there are other ways to scale it, and improve it overall. That&#8217;s the gist of Redux.</p>



<h3 class="wp-block-heading">Why Are We Using This?</h3>



<p>When building applications in React, you need some sort of state and need it placed somewhere. For some applications, most of it can reside in the URL in the form of GET variables. For others, it&#8217;s simply a global variable.  For others, if you load a list from the server, you&#8217;ll store that in a components <code>props</code> or even <code>state</code> for class components, or a closure for Hooks. Some keep it in sessions.</p>



<p>Eventually, though, some applications need 2 things that the above doesn&#8217;t provide: the ability to share the same data between multiple components, and the ability to update that data from any place you need. Sometimes an <a href="https://sourcemaking.com/design_patterns/mediator">OOP Mediator design pattern</a>, <a href="https://reactjs.org/docs/higher-order-components.html">higher order components</a>, or even just component composition works. You do this to avoid passing props down many component levels, or the components themselves via higher order components. You have a parent component who&#8217;s sole job is to handle communication between a bunch of children components.</p>



<p>As things grow, rather than utilize a <a href="https://martinfowler.com/eaaDev/uiArchs.html">Model View Controller</a> style architecture, React provided <a href="https://reactjs.org/docs/context.html">Context</a>. They describe it as a &#8220;tree&#8221;, from the idea that a component made of many components forms a tree, much like html within html forms a tree of nodes. When many in the tree, or even sibling components need to share the same data, and communicate up and down, performance aside, Context is the go to.</p>



<p>If, however, you want something deterministic without any state that can be mutated or &#8220;changed&#8221;, you use Redux. While people will often use Redux for the same reasons they use Context, the whole point is to ensure predictable code. If you only have 1 variable, you can ensure that the rest of your code is pure functions. If the rest of your code is pure functions, they&#8217;re predictable and easier to test. That means the bugs are typically type related, race conditions, CSS, or null pointers in your component code or 3rd party libraries. If your component code is intentionally dumb, small, and using Hooks in function components over classes, then you&#8217;re significantly reducing the places bugs can hide.</p>



<p>In short, all your code uses <code>const</code> and pure functions as much as possible, and all the hard work is in Redux reducers with as little code as possible in your React components and Hooks. Redux hides from you the only <code>var</code> (or <code>let</code>, heh) in the entire application. Now your application has only 1 variable which is your Model. All data is there, easy to find, and as your application grows, your Model just gets more branches on the Object. Given how JavaScript works, creating immutable versions of just pieces of tree means components see only the part they care about, and in turn the reducers only change the part they care about.</p>



<h2 class="wp-block-heading">Redux Thunk</h2>



<p>The above code is all synchronous. JavaScript applications are often asynchronous. The web browser is asynchronous because the code that renders the screen is also the code that loads image.</p>



<p>Redux&#8217; default <code>store</code> doesn&#8217;t have the ability to deal with <code>Promises</code> or any type of callback async style. The <a href="https://github.com/reduxjs/redux-thunk">redux-thunk library</a> was created to make that as simple as possible.</p>



<p>An example would be <a href="http://jessewarden.com/2019/02/easier-asynchronous-state-modelling-in-react-redux-or-hooks.html">modelling ajax calls</a>. For example, the UI below shows the 3 possible states: loading, error, success:</p>



<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="1441" height="820" src="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1.png" alt="" class="wp-image-5798" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1.png 1441w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-300x171.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-768x437.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-1024x583.png 1024w" sizes="(max-width: 1441px) 100vw, 1441px" /></figure>



<figure class="wp-block-image"><img decoding="async" width="1441" height="820" src="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM.png" alt="" class="wp-image-5799" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM.png 1441w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-300x171.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-768x437.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-1024x583.png 1024w" sizes="(max-width: 1441px) 100vw, 1441px" /></figure>



<figure class="wp-block-image"><img decoding="async" width="1024" height="623" src="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-1024x623.png" alt="" class="wp-image-5800" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-1024x623.png 1024w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-300x183.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-768x467.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM.png 1441w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Putting that in a Redux Store would look something like:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">{
  <span class="hljs-attr">loadingState</span>: {
    <span class="hljs-attr">loading</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">isError</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">error</span>: <span class="hljs-literal">undefined</span>,
    <span class="hljs-attr">data</span>: <span class="hljs-literal">undefined</span>
  }
}</code></span></pre>


<p>Or using Algebraic Data Types:</p>


<pre class="wp-block-code"><span><code class="hljs language-css">{
  <span class="hljs-attribute">loadingState</span>: <span class="hljs-built_in">LoadingFoods</span>()
}</code></span></pre>


<p>You dispatch an Action Creator before the AJAX call to put it in a loading state, when it fails you dispatch an error Action Creator, or when it succeeds, you dispatch a success Action Creator.  Using a Promise, it looks like this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">dispatch(loadingFoods())
fetch(<span class="hljs-string">'/foods'</span>)
.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> result.json())
.then(<span class="hljs-function"><span class="hljs-params">foods</span> =&gt;</span> dispatch(foodsLoaded(foods))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> dispatch(foodsFailed(error))</code></span></pre>


<h3 class="wp-block-heading">Connecting Redux to React</h3>



<p>Now that you have Redux and Thunks for async calls, you now wire up to React, usually using the <a href="https://redux.js.org/basics/usage-with-react">connect library</a>. A pattern emerges where you&#8217;ll have &#8220;dumb&#8221; components who take data, render it, or are just simple UI elements like &lt;buttons&gt;, etc. You then have &#8220;connected&#8221; components that know about Redux. Their sole job is to provide an interface for a React component to get its data from the current state, and when the component has events, those trigger Action Creators. This requires 2 functions called <code>mapStateToProps</code> and <code>mapDispatchToProps</code> and put you those 2 in the <code>connect</code> call with your Component, and it smooshes them together into a &#8220;ConnectedComponent&#8221;. If you have a <code>Cow</code> component, and connect it to Redux, it&#8217;ll be a <code>ConnectedCow</code>. </p>



<p>An example React component that would show 3 screens needs 1 piece of data to know what screen to show, and 1 click handler when the user clicks &#8220;reload&#8221;. </p>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">Screen</span> <span class="hljs-attr">loading</span>=<span class="hljs-string">{true}</span> <span class="hljs-attr">reloadClicked</span>=<span class="hljs-string">{reloadClicked}</span> /&gt;</span></code></span></pre>


<p>To get data, you create a function called <code>mapStateToProps</code>. The longer version is &#8220;Yo, I&#8217;ll give you the current Redux state in the store; you can either use it as is, even if it&#8217;s a gigantic Object, or you can snag off the pieces you want. Whatever you return to me, I&#8217;ll set as the props to your component for you. Also, don&#8217;t worry, I&#8217;ll get called every time the data you care about changes.&#8221; Since the whole point of using React is to keep your DOM in sync with your data, this is a perfect match.</p>



<p>Given our example Object above of modelling the loading state, it&#8217;d be:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> mapStateToProps = <span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.loadingState</code></span></pre>


<p>Second, we need a <code>mapDispatchToProps</code>. This function takes any events that come out of our React component, and makes it fire the <code>dispatch</code> action creator we want. If we want to click a &lt;button&gt; in the component and have it go <code>dispatch(reloadActionCreator())</code>, then we need to give our component a function to do that. The <code>mapDispatchToProps</code> wants you to return an Object that it&#8217;ll put on the component&#8217;s <code>props</code> for you, and it gives you the Redux <code>dispatch</code> function so you can use it in a sync or async way. We&#8217;ve got just 1 event in our React component that looks like this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> Screen = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading: {props.loading}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{props.reloadClicked}</span>&gt;</span>Reload<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)</code></span></pre>


<p>So we&#8217;ll create that <code>reload</code> function for it like so:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> mapDispatchToProps = <span class="hljs-function"><span class="hljs-params">dispatch</span> =&gt;</span>
    ({
        <span class="hljs-attr">reloadClicked</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> dispatch(reloadActionCreator())
    })</code></span></pre>


<p>Last part is to smoosh them together via <code>connect</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> ConnectedScreen = connect(
  mapStateToProps,
  mapDispatchToProps
)(Screen)</code></span></pre>


<h2 class="wp-block-heading">Elm Architecture</h2>



<p>Below is a crash course in the Elm Architecture. It can be a LOT to take in, even if you&#8217;ve had extensive Redux experience. Don&#8217;t fret, and read the <a href="https://guide.elm-lang.org/">Elm Guide</a> multiple times, it&#8217;ll click.</p>



<p>Elm comes built-in with the Elm Architecture. There is no way to NOT use the Elm architecture, unless you&#8217;re playing around with Elm code in the <code>elm repl</code>. If you&#8217;re familiar with Redux, then you&#8217;ll understand the Elm architecture.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="804" height="758" src="https://jessewarden.com/wp-content/uploads/2019/10/elm-architecture.001.png" alt="" class="wp-image-5876" srcset="https://jessewarden.com/wp-content/uploads/2019/10/elm-architecture.001.png 804w, https://jessewarden.com/wp-content/uploads/2019/10/elm-architecture.001-300x283.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/elm-architecture.001-768x724.png 768w" sizes="auto, (max-width: 804px) 100vw, 804px" /></figure>



<p>Similar to Redux, you have a model that is your data. In Redux, it&#8217;s some Object that grows over time. In Elm, it&#8217;s a <a href="https://elm-lang.org/docs/records">Record</a> that grows over time. The difference is Elm has types to ensure the Model&#8217;s values are changed correctly.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">type alias Model =
  { <span class="hljs-attr">firstName</span> : <span class="hljs-built_in">String</span>
  , <span class="hljs-attr">lastName</span> : <span class="hljs-built_in">String</span> }

initialModel =
  { firstName = <span class="hljs-string">"???"</span>
  , lastName = <span class="hljs-string">"Warden"</span> }</code></span></pre>


<p>Think of <code>type alias</code> as a JavaScript <code>class</code>. You can instantiate new <code>type alias</code> things. To change the <code>Model</code>, you send <code>Messages</code>. They&#8217;re just types too. They&#8217;re like Redux Actions. Instead of <code>{ type: 'UpdateFirstName' }</code>, it&#8217;s <code>UpdateFirstName</code>. You don&#8217;t need Action Creators like you do in JavaScript since the compiler will ensure you create them correctly.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">type Msg
  = UpdateFirstName <span class="hljs-built_in">String</span>
  | UpdateLastName <span class="hljs-built_in">String</span></code></span></pre>


<p>You handle those Messages in the <code>update</code> function just like you handle Actions in Redux reducer functions. Elm will not compile unless you handle all of them. In JavaScript you can intentionally ignore Actions you don&#8217;t understand by using <code>default</code> at the bottom of the switch statement. You can also forget as your application grows and you miss one and have no compiler to yell at you. The code below ignores an action with the type &#8220;updateLastName&#8221;.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> personReducer = <span class="hljs-function">(<span class="hljs-params">person, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'updateFirstName'</span>:
      <span class="hljs-keyword">return</span> firstNameReducer(person, action)
    <span class="hljs-attr">default</span>:
      <span class="hljs-keyword">return</span> person
  }
}</code></span></pre>


<p>Not so in Elm. This only handles <code>UpdateFirstName</code>. Elm won&#8217;t compile until you implement it correctly.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">update message model =
  <span class="hljs-keyword">case</span> message <span class="hljs-keyword">of</span>
    UpdateFirstName firstName -&gt;
      { model | firstName = firstName }</code></span></pre>


<p>Check out this beastly compiler error:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">Missing Patterns
Line <span class="hljs-number">26</span>, Column <span class="hljs-number">5</span>
This <span class="hljs-string">`case`</span> does not have branches <span class="hljs-keyword">for</span> all possibilities:

<span class="hljs-number">26</span>|&gt;    <span class="hljs-keyword">case</span> msg <span class="hljs-keyword">of</span>
<span class="hljs-number">27</span>|&gt;        UpdateFirstName firstName -&gt;
<span class="hljs-number">28</span>|&gt;          { model | firstName = firstName }

Missing possibilities include:

    UpdateLastName _

I would have to crash <span class="hljs-keyword">if</span> I saw one <span class="hljs-keyword">of</span> those. Add branches <span class="hljs-keyword">for</span> them!

Hint: If you want to write the code <span class="hljs-keyword">for</span> each branch later, use <span class="hljs-string">`Debug.todo`</span> <span class="hljs-keyword">as</span> a
placeholder. Read &lt;https:<span class="hljs-comment">//elm-lang.org/0.19.0/missing-patterns&gt; for more</span>
guidance on <span class="hljs-keyword">this</span> workflow.</code></span></pre>


<p>Fixing our code to handle both Messages by now including the <code>UpdateLastName</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">update message model =
  <span class="hljs-keyword">case</span> message <span class="hljs-keyword">of</span>
    UpdateFirstName firstName -&gt;
      { model | firstName = firstName }
    UpdateLastName lastname -&gt;
      { model | lastName = lastName }</code></span></pre>


<p>The <code>view</code> function gets the <code>Model</code> as the first parameter. There&#8217;s no need to setup components to be aware of it like in React via the connect function for Redux. They are just functions and can take the Model as a parameter, or parts of it. It&#8217;s up to you. In Redux, you&#8217;d use <code>mapStateToProps</code>. The connect library will then spread all the data you need on your React component <code>props</code>. In Elm, you just get the whole model. You&#8217;re welcome to snip off the pieces you want, though.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">view model =
  div &#91;] &#91; text <span class="hljs-string">"First Name: "</span> ++ model.firstName ]</code></span></pre>


<p>When you&#8217;re ready to make HTTP calls, your update function is returned to send back 2 values instead of just the model. In Redux, you get the model and action, but only have to return the model. Below is the Redux reducer for the loading state:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> loadingState = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'loading'</span>:
      <span class="hljs-keyword">return</span> {...state, <span class="hljs-attr">loading</span>: <span class="hljs-literal">true</span>}
    <span class="hljs-keyword">case</span> <span class="hljs-string">'error'</span>:
    <span class="hljs-keyword">case</span> <span class="hljs-string">'success'</span>:
      <span class="hljs-keyword">return</span> {...state, <span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>}
  }
}</code></span></pre>


<p>You&#8217;ll then have code elsewhere that dispatches the Action, then makes the <code>fetch</code> call, then dispatches either an Error or Success Action.</p>



<p>In Elm, you can&#8217;t make HTTP calls on your own since those are side effects. Instead, you use a Command. You don&#8217;t typically create Commands on your own. Rather, things that cause side effects like HTTP calls create them for you, you just return them in your <code>update</code> function so Elm knows what to do.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">update model =
  LoadData -&gt;
    ( { model | state = <span class="hljs-string">"loading"</span> }
      , Http.get
      { url = <span class="hljs-string">"/companies"</span>
      , expect = Http.expectString CompaniesHTTPResult
      }
    )
  ...</code></span></pre>


<p>That <code>Http.get</code> returns a Command. Elm internally will make the call for you. Whenever the HTTP result is successful or fails, your <code>update</code> will be called again some time later with your <code>CompaniesHTTPResult</code> message. Think of the <code>error</code> and <code>success</code> in the JavaScript Redux reducer above as one <code>CompaniesHTTPResult</code> below. The <code>result</code> parameter lets you know if it worked or not.</p>


<pre class="wp-block-code"><span><code class="hljs">update model =
  CompaniesHTTPResult result -&gt;
    -- it's either Ok or Err</code></span></pre>


<p>This concept of just having functions either return data or Commands seems weird at first. In JavaScript you&#8217;re used to &#8220;making it do&#8221;. Things like &#8220;make this GET request and wait for it&#8221;, or &#8220;Read this data from Application Cache&#8221;. In Elm, you can do those things, but it&#8217;s all through returning Commands in the <code>update</code> function. Elm will handle the nitty gritty of making the actual XHR call, or reading from the browser&#8217;s storage. You&#8217;ll typically have a <code>Message</code> to &#8220;kick it off&#8221;. This means there is no need for a Thunk. No need for a mapping function of events to dispatches. Your UI will trigger messages, and inside the update function, you can then return Commands to do side effect things. </p>



<h2 class="wp-block-heading">Bugs in React</h2>



<p>Bugs in React are usually because of JavaScript. The language is fast to develop in and run with no compile step. This speed comes at the cost of having little to no correctness guarantees when you run. Maybe it&#8217;ll work, maybe it won&#8217;t. That is a adrenaline rush for some people, myself included.</p>



<p>However, some errors aren&#8217;t even reported. They&#8217;re &#8220;swallowed&#8221;. Meaning, your application doesn&#8217;t work like you expect, but you don&#8217;t get an exception. No stack trace, no error, no red in the console, no error breakpoint triggered&#8230; just &#8220;what&#8230; the&#8230;.&#8221;. These are the worst because at least Exceptions give you a possible hint and path to follow. At least returned Errors from more functional code can also give a hint and a path.</p>



<p>Below, I&#8217;ve listed some common ones not always caught by ESLint plugins via misspellings, lack of types, null pointers, missing case statements, and logic errors.</p>



<h3 class="wp-block-heading">Swallowed Errors via Misspellings</h3>



<p>In JavaScript, you can name Object properties just about anything you want. The problem is when it&#8217;s accidental and <code>onClick</code> becomes <code>onClck</code>. JavaScript doesn&#8217;t know you meant  <code>onClick</code>, and if you pass React event handlers <code>undefined</code>, they&#8217;ll assume you want nothing to happen. One mispelling, 2 miscommunications. Worse? It&#8217;s silent; you won&#8217;t get any runtime exception. You click a button and nothing happens. </p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="730" height="400" src="https://jessewarden.com/wp-content/uploads/2019/10/accounts-no-click-1.gif" alt="" class="wp-image-5870"/></figure>



<p><a href="https://eslint.org/">ESLint</a> plugins can only help so much. Some code can only be known to work together if it&#8217;s run, and some variables aren&#8217;t known to each other unless you had types and a compiler.</p>



<p>In Elm, every single variable&#8217;s spelling must match a known type, or it won&#8217;t compile. With the exception of magic strings, this completely solves swallowed errors via misspellings.</p>



<h3 class="wp-block-heading">Null Pointers Because of the Lack of Types</h3>



<p>You can use Algebraic Data Types in JavaScript. This allows you to return a <a href="https://folktale.origamitower.com/api/v2.3.0/en/folktale.result.html">Result</a> from an operation that could fail, either success or failure. It&#8217;s called an <code>Either</code> in some Functional languages, but in JavaScript, the default one is a <code>Promise</code>. However, Promises don&#8217;t come with the popular matching syntax where as something like <code>Result</code> from Folktale or <a href="https://github.com/true-myth/true-myth">true-myth</a> do.</p>



<p>Downside? You have to memorize the variable names, specifically how you destructure. Without types, you can get subtle bugs that can inadvertently get swallowed. In Redux, since all of the code is synchronous, it&#8217;s easier and more fun to use <code>Result</code> as opposed to <code>Promise</code> because the code is synchronous, can be chained like Promise, and has <a href="https://github.com/tc39/proposal-pattern-matching">matching syntax</a>. In our reducer below, if the ajax call to load the accounts works, great, we parse it and return a success. If not, we return a failure. The UI can match on this to know what to draw. </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> accounts = <span class="hljs-function">(<span class="hljs-params">state=AccountsNotLoaded(</span>), <span class="hljs-params">action</span>) =&gt;</span> {
      ...
      case <span class="hljs-string">'fetchAccountsResult'</span>:
          <span class="hljs-keyword">return</span> action.fetchResult.matchWith({
            <span class="hljs-attr">Ok</span>: <span class="hljs-function">(<span class="hljs-params">{ value }</span>) =&gt;</span> {
                ...
                AccountsLoadSuccess(...)
            },
            <span class="hljs-attr">Error</span>: <span class="hljs-function">(<span class="hljs-params">{ error }</span>) =&gt;</span>
              AccountsLoadFailed(error)
          })</code></span></pre>


<p>The bug is both <code>Ok</code> and <code>Error</code> have a <code>value</code> to destructure. That means <code>AccountsLoadFailed(error)</code> is actually <code>AccountsLoadFailed(undefined)</code>. This ends up on the React UI and causes a null pointer:</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="244" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM-1024x244.png" alt="" class="wp-image-5859" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM-1024x244.png 1024w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM-300x72.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM-768x183.png 768w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-12.33.04-PM.png 1804w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>That&#8217;s because the <code>error</code> is actually <code>undefined</code> and when you go <code>undefined.anything</code> it blows up. Types in Elm won&#8217;t compile if you misspell things or spell the wrong thing because you haven&#8217;t learned the API yet.</p>



<p>In Elm, you have types and a compiler to help ensure that never happens.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">FetchAccountsResult result -&gt;
        <span class="hljs-keyword">case</span> result <span class="hljs-keyword">of</span>
          Ok accountJSONs -&gt;
            ...
            { model | accountState = AccountsLoadSuccess accounts }
          Err datError -&gt;
            { model | accountState = AccountsLoadFailed (httpErrorToString datError) }</code></span></pre>


<p>In the Elm code above, the <code>AccountsLoadFailed</code> is defined as <code>AccountsLoadFailed String</code>. If you were to pass the error itself like <code>AccountsLoadFailed datError</code>, the compiler wouldn&#8217;t compile your code, saying you&#8217;re passing an <code>Error</code> when you should be passing a <code>String</code>.  Using types and a compiler, Elm ensures you&#8217;ll never get null pointers at runtime. You still have to do the work to build an error UI and format the errors for viewing.</p>



<h3 class="wp-block-heading">Missing Case Statements</h3>



<p>Missing case statements can bite you in 2 places in React. The first is in your reducers. If you miss a case statement, you get no indication you did beyond your application doesn&#8217;t work correctly. Below is a reducer that handles all 4 things you can do in the example app; loading the data, parsing the response, and pressing the next/back buttons.</p>


<pre class="wp-block-code"><span><code class="hljs language-php">accounts = (state=AccountsNotLoaded(), action) =&gt; {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'fetchAccounts'</span>:
      ...
    <span class="hljs-keyword">case</span> <span class="hljs-string">'fetchAccountsResult'</span>:
      ...
    <span class="hljs-keyword">case</span> <span class="hljs-string">'previousAccountPage'</span>:
      ...
    <span class="hljs-keyword">case</span> <span class="hljs-string">'nextAccountPage'</span>:
      ...
    <span class="hljs-keyword">default</span>:
      ...
  }
}</code></span></pre>


<p>What happens when you forget one? We&#8217;ll comment out the <code>'fetchAccountsResult'</code> one.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="225" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM-1024x225.png" alt="" class="wp-image-5862" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM-1024x225.png 1024w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM-300x66.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM-768x169.png 768w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-1.57.36-PM.png 1908w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>You&#8217;ll now see the loading UI forever. You won&#8217;t know if this is because the server is slow or your code is broken. If you&#8217;re using TypeScript in strict-mode, and you convert your case strings to actual <code>type</code>&#8216;s, TypeScript won&#8217;t compile because you haven&#8217;t handled every potential case.</p>



<p>The 2nd place is forgetting the <code>default</code>. Again, TypeScript can help here.</p>



<p>The 3rd place, and is more dealing with Algebraic Data Types, is the matching syntax. For example, if our server is down, but we forget to render that part of the UI in the React component:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> AccountStates = <span class="hljs-function">(<span class="hljs-params">{ accountsState }</span>) =&gt;</span>
  accountsState.matchWith({
    <span class="hljs-attr">AccountsNotLoaded</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Accounts not fetched yet.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>),
    <span class="hljs-attr">AccountsLoading</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading accounts...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>),
    <span class="hljs-attr">AccountsLoadNothing</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>No accounts.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>),
    <span class="hljs-comment">// AccountsLoadFailed: ({ value }) =&gt; (&lt;div&gt;{value.message}&lt;/div&gt;),</span>
    <span class="hljs-attr">AccountsLoadSuccess</span>: <span class="hljs-function">(<span class="hljs-params">{ accountView }</span>) =&gt;</span> (...)
  })</code></span></pre>


<p>Notice the above code has <code>AccountsLoadFailed</code> commented out. That means, if the server fails, you get the following null pointer error:</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="715" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM-1024x715.png" alt="" class="wp-image-5863" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM-1024x715.png 1024w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM-300x209.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM-768x536.png 768w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.01.59-PM.png 1768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>In Elm, every case statement is basically the matching syntax. With the compiler, this ensures you will never miss a case. Below, I have a <code>Result</code> when the Account REST call returns. It either worked or it didn&#8217;t:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">FetchAccountsResult result -&gt;
      <span class="hljs-keyword">case</span> result <span class="hljs-keyword">of</span>
        Ok json -&gt;
          ...
        Err error -&gt;
          ...</code></span></pre>


<p>However, if I forget the <code>Err</code>, then I&#8217;ll get a compiler error: </p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="830" height="336" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.09.20-PM.png" alt="" class="wp-image-5864" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.09.20-PM.png 830w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.09.20-PM-300x121.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-2.09.20-PM-768x311.png 768w" sizes="auto, (max-width: 830px) 100vw, 830px" /></figure>



<p>Elm ensures you never forget a case statement, including <code>default</code>. </p>



<h3 class="wp-block-heading">Logic Error: Off By 1</h3>



<p>Even if all your code doesn&#8217;t have null pointer exceptions, and you handle all possible case statements, you can still have logic errors. It&#8217;s where your code doesn&#8217;t explode, but doesn&#8217;t work like you want it to. Both the React app and Elm app can have this same bug.</p>



<p>When you click the next and back buttons in the application, they increment what page you are in. If we can&#8217;t increment anymore, we do nothing and stay on the same page. There is a bug in this function, specifically the  <code>accountView.currentPage &lt; accountView.pageSize</code>. We&#8217;ll come back to this below. We&#8217;ve implemented this in the Redux reducer:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> nextPage = <span class="hljs-function"><span class="hljs-params">accountView</span> =&gt;</span> {
    <span class="hljs-keyword">if</span>(accountView.currentPage &lt; accountView.pageSize) {
      <span class="hljs-keyword">return</span> {...accountView, <span class="hljs-attr">currentPage</span>: accountView.currentPage + <span class="hljs-number">1</span>}
    }
    <span class="hljs-keyword">return</span> accountView
  }</code></span></pre>


<p>Using that number as the index to the Array, you can determine which page you should show. We use this awesome <a href="https://lodash.com/docs/4.17.15#chunk">chunk</a> function from Lodash that takes your Array and automatically creates pages from it. So if you&#8217;re array is <code>[1, 2, 3, 4, 5, 6, 7]</code> and you want 3 pages, you go <code>chunk(3, yourArray)</code> and it&#8217;ll give you an Array that looks like <code>[ [1, 2, 3], [4, 5, 6], [7] ]</code>. If your current page is 0, then you&#8217;ll draw a list of <code>[1, 2, 3]</code>. If you&#8217;re current page is 2, then you&#8217;ll draw a list of <code>[7]</code>.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> getCurrentPage = <span class="hljs-function"><span class="hljs-params">pageSize</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">currentPage</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">accounts</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> chunked = chunk(pageSize)(accounts)
  <span class="hljs-keyword">if</span>(isNil(chunked&#91;currentPage])) {
    <span class="hljs-keyword">return</span> &#91;]
  }
  <span class="hljs-keyword">return</span> chunked&#91;currentPage]
}</code></span></pre>


<p>When you run the application, it allow works, and you can click the next button to cycle through the pages. However, a logic error arises at the end. Once there, the screen goes blank, the numbers show 11 of 10, and you can no longer click the back button. There are no null pointers caught by React, and the console doesn&#8217;t show any issues. Wat.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="356" src="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM-1024x356.png" alt="" class="wp-image-5868" srcset="https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM-1024x356.png 1024w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM-300x104.png 300w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM-768x267.png 768w, https://jessewarden.com/wp-content/uploads/2019/10/Screen-Shot-2019-10-03-at-6.26.58-PM.png 1912w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>The first bug as explained above is how you increment the pages:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">if</span>(<span class="hljs-selector-tag">accountView</span><span class="hljs-selector-class">.currentPage</span> &lt; <span class="hljs-selector-tag">accountView</span><span class="hljs-selector-class">.pageSize</span>) {</code></span></pre>


<p>That means you can increment the current page, which starts at 0, to 10 since there are 10 pages and pageSize is 10. The problem is, Array&#8217;s are 0 based, and 0 counts as a number. So now you have the ability to next to 11 pages. That logically should not be allowed, but your code allows it. The function the way it is written, being typed with TypeScript, or even Elm would still result in the same logic error of being off by 1 number.</p>



<p>We fix it by adding a 1 to our page size:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">if</span>(<span class="hljs-selector-tag">accountView</span><span class="hljs-selector-class">.currentPage</span> &lt; <span class="hljs-selector-tag">accountView</span><span class="hljs-selector-class">.pageSize</span> + 1) {</code></span></pre>


<p>Now the current page will never exceed 9 which is the last item in the Array of 10 items.</p>



<h2 class="wp-block-heading">Errors in Elm</h2>



<p>There are no null pointers in Elm; that&#8217;s one of the main draws to using it. When you compile, you will NOT get runtime errors.</p>



<p>Sort of. The marketing isn&#8217;t as clear as it could be on this. Let&#8217;s break down the 3 types of errors you can and cannot get in Elm. You won&#8217;t get null pointers like you do in JavaScript. There are 2 exceptions to this. The first is when you are in development mode and log out enough JSON that you cause the browser to run out of memory eventually causing the page to crash. The second is when you are integrating with JavaScript through ports and the JavaScript crashes the application by either throwing an error or disobeying the port&#8217;s rules.</p>



<p>The third errors are built into Elm as an Algebraic Data Type: <code>Error</code>. They&#8217;re just like Folktale/true-myth&#8217;s Error type and are encouraged to be used, returning them from functions that can fail. The lack of data such as <code>undefined</code> which typically causes errors in JavaScript is called a <code>Maybe</code> in Elm. It&#8217;s actually embraced in Elm as a type, just like <code>Error</code> to prevent null pointers from ever occurring.</p>



<p>We&#8217;ll focus on the <code>Maybe</code>, <code>Error</code>, and logic errors below since ports and safely working with JavaScript is beyond this article&#8217;s scope. You can <a href="https://guide.elm-lang.org/interop/ports.html">read more about ports</a> in the official guide.</p>



<h3 class="wp-block-heading">Null Pointers</h3>



<p>Most null pointers you get in JavaScript result from trying to dot on an <code>undefined</code> like <code>this.someMethod()</code> in a <code>class</code> or:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> value = getSomething()
<span class="hljs-keyword">const</span> result = value.something</code></span></pre>


<p>If the <code>value</code> returned is <code>undefined</code>, then instead of <code>value.something</code>, what actually happens is <code>undefined.something</code> and that causes a null pointer.</p>



<p>Null pointers also happen because you misspell things. Either the code fails immediately, or later with some subtle bug because the name you placed was on an Object property name instead of a variable or instance, and you don&#8217;t find out till later.</p>



<p>None of those bugs can&#8217;t happen in Elm. You&#8217;ll never have scope problems because Elm doesn&#8217;t have any. Classes hide state, and Elm is a functional language that doesn&#8217;t allow you to create any state. No classes, no <code>this</code>. You can store things in the Model and it feels like a variable (<code>let</code> or <code>var</code>), but any changes you make are immutable. There are no classes to hide mutations.</p>



<p>The second reason the dots never fail in Elm is because of the type system. If you can guarantee that all Objects (called Records in Elm) match the types exactly, then you know exactly if you can dot or something or not. Here is a <code>Person</code> type alias; think of it like a class you can instantiate:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">type alias Person =
  { <span class="hljs-attr">firstName</span> : <span class="hljs-built_in">String</span>
  , <span class="hljs-attr">age</span> : Int }</code></span></pre>


<p>Now you can create a <code>Person</code> by simply going:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span> <span class="hljs-number">40</span></code></span></pre>


<p>The compiler will check this for you and allow it. If you did this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">'Jesse'</span> <span class="hljs-number">40</span></code></span></pre>


<p>It wouldn&#8217;t compile because single quotes are used for characters. If you did this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span> <span class="hljs-number">40.2</span></code></span></pre>


<p>It wouldn&#8217;t work because 40.2 is a <code>Float</code>, not an <code>Int</code>. If you did this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span>
msg = log <span class="hljs-string">"firstName: "</span> myPerson.firstName</code></span></pre>


<p>It wouldn&#8217;t work because myPerson is a partial application; it&#8217;s a function waiting for you to give it an <code>Int</code> so it can make a person. Since it&#8217;s a function, it has no <code>firstName</code> property so the program won&#8217;t compile. Technically it&#8217;s type is <code>Int -&gt; Person</code>.</p>



<p>If you log out the name, it works fine:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span> <span class="hljs-number">40</span>
msg = log <span class="hljs-string">"firstName: "</span> myPerson.firstName</code></span></pre>


<p>But if you misspell <code>firstName</code> to have a missing &#8220;i&#8221;:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">myPerson = Person <span class="hljs-string">"Jesse"</span> <span class="hljs-number">40</span>
msg = log <span class="hljs-string">"firstName: "</span> myPerson.frstName</code></span></pre>


<p>Elm won&#8217;t compile and will suggest maybe you meant <code>firstName</code>.</p>



<p>The third place you can get null pointers in JavaScript is when your code is good, and the data it creates is good and predictable, but then you get JSON from some other place like a web service. When the JSON changes, or they send you HTML instead of JSON, suddenly your functions are acting weird because they don&#8217;t know what HTML is, or the Objects they thought they were getting in JSON have slightly different names or a slightly different structure.</p>



<p>In Elm, all JSON into Elm is parsed using strict decoders. This ensures that no untyped values that could cause a null pointer get into Elm from HTTP calls and JavaScript. If JavaScript passes you a <code>Person</code> like the above, it&#8217;ll either work, or fail to parse. There is no middle ground here.</p>



<h3 class="wp-block-heading">Maybe</h3>



<p>Since there is no way to create an <code>undefined</code> or <code>null</code> in Elm, then how do you deal with things that don&#8217;t return anything? In cases where you might not get a value back, Elm provides a <code>Maybe</code> type. It allows you get a value wrapped in something called a <code>Just</code> or when you don&#8217;t have a value, it&#8217;s a <code>Nothing</code>. This forces your functions to suddenly handle the case when they get nothing back. Our JavaScript function above for getting the current page, you saw that it handled if it got <code>undefined</code> back, then it defaulted to an empty <code>Array</code>. This is a great practice and acts like a <code>Maybe</code>. However, not all functions in JavaScript handle this case and all you have to do is miss one, and POW, null pointer.</p>



<p>Since Elm has types, it knows what a <code>Maybe</code> is. This means if you mess up, misspell it, or only handle the <code>Just</code>, it won&#8217;t compile until you fix it. For example, if you get an item from an Array but the Array is empty, you&#8217;ll get a <code>Nothing</code> back. If the Array is full of things, and you ask for the first item, you&#8217;ll get a <code>Just</code> back. There is no way to know until runtime, though, so Elm ensures you handle both:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">getFirstPersonsName = 
  <span class="hljs-keyword">case</span> <span class="hljs-built_in">Array</span>.get <span class="hljs-number">0</span> peopleList <span class="hljs-keyword">of</span>
    Just item -&gt;
      item.firstName
    Nothing -&gt;
      <span class="hljs-string">"Nobody is in the list."</span></code></span></pre>


<p>If you leave out the <code>Nothing</code>, Elm won&#8217;t compile your code, letting you know you need to handle the <code>Nothing</code> case. This is true for all functions, and ensures your entire program cannot be broken by 1 missing value.</p>



<h3 class="wp-block-heading">Error Type</h3>



<p>There are functions that can work or fail. These are different than <code>Maybe</code>&#8216;s. In the case of loading data from a back-end web service, it&#8217;ll either work or it won&#8217;t. Sure, you could get back an empty <code>Array</code> which could count as a <code>Nothing</code>, but there are a litany of things that could go wrong instead. All you want to know is &#8220;Did it work? Let me know and give me the value, otherwise give the error so I can show it.&#8221;</p>



<p>Unlike exceptions in JavaScript, however, there is no <code>throw</code> in Elm, nor any <code>try/catch</code>. There are also no <a href="https://reactjs.org/docs/error-boundaries.html">error boundaries</a> like in React. If a function can fail, you return an <code>Ok</code> or an <code>Err</code>. If you need to handle that in your UI, you do a case statement to draw a different UI for each piece:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-selector-tag">case</span> <span class="hljs-selector-tag">httpResult</span> <span class="hljs-selector-tag">of</span>
  <span class="hljs-selector-tag">Ok</span> <span class="hljs-selector-tag">data</span> <span class="hljs-selector-tag">-</span>&gt;
    <span class="hljs-selector-tag">div</span> <span class="hljs-selector-attr">&#91;]</span> <span class="hljs-selector-attr">&#91; text (<span class="hljs-string">"Yay, data: "</span> ++ data) ]</span>
  <span class="hljs-selector-tag">Err</span> <span class="hljs-selector-tag">reason</span> <span class="hljs-selector-tag">-</span>&gt;
    <span class="hljs-selector-tag">div</span> <span class="hljs-selector-attr">&#91;]</span> <span class="hljs-selector-attr">&#91; text (<span class="hljs-string">"Bummer, an error: "</span> ++ (httpErrorToString reason))]</span></code></span></pre>


<h2 class="wp-block-heading">Logic Errors</h2>



<p>Null pointers are fixed by types and <code>Maybe</code>&#8216;s. Errors are handled by the <code>Error</code> type. Encoding/decoding is handled by the JSON Decoder/Encoder modules to ensure only typed data gets in. If you&#8217;re going to use Port&#8217;s, you already accepted you&#8217;re in dangerous territory. So no more bugs right?</p>



<p>Sadly, Elm too can still have logic errors. Types CAN help here, but they&#8217;re not a panacea. Either you don&#8217;t know the data type your need, or haven&#8217;t written the appropriate unit test, or didn&#8217;t know you needed to.</p>



<p>Our Elm code can have the same bug as the React app where it increments the next page too high:</p>


<pre class="wp-block-code"><span><code class="hljs language-xml">nextPage accountView =
  if accountView.currentPage <span class="hljs-tag">&lt; <span class="hljs-attr">accountView.pageSize</span> <span class="hljs-attr">then</span>
    { <span class="hljs-attr">accountView</span> | <span class="hljs-attr">currentPage</span> = <span class="hljs-string">accountView.currentPage</span> + <span class="hljs-attr">1</span>}
  <span class="hljs-attr">else</span>
    <span class="hljs-attr">accountView</span></span></code></span></pre>


<p>Again, you need to remember Array&#8217;s are 0 based, so have to ensure <code>currentPage</code> can only be 0 through 9. You fix that by <code>accountView.currentPage &lt; accountView.pageSize + 1</code>.</p>



<p>Before you start writing unit and functional tests, though, remember you have a pretty good type system in Elm. Can you create a type that prevents this bug from happening? Making an impossible state, impossible to happen? <a href="https://www.youtube.com/watch?v=IcgmSRJHu_8">Richard Feldman talks about these types of data types in his talk</a>. There are a lot of these types of data types that, once learned, ensure you&#8217;ll never get into an impossible state, and don&#8217;t even need unit tests for it.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="&quot;Making Impossible States Impossible&quot; by Richard Feldman" width="500" height="281" src="https://www.youtube.com/embed/IcgmSRJHu_8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Conclusions</h2>



<h3 class="wp-block-heading">React, JavaScript, Redux, and Thunks</h3>



<p>React uses JavaScript, Redux, and Thunks. JavaScript is a dynamic language that, even with various tooling, you still have to run it to see if it works. The speed of development is great for fleshing out ideas and quickly iterating. The cost of that speed is null pointer exceptions, swallowed errors, many are just because of misspellings. This is compounded by the most libraries installed via npm being also written in JavaScript.</p>



<p>React helps with a few of these challenges by optionally providing PropTypes which allow better error messages at runtime. It also allows global error handling via error boundaries with fallback UI&#8217;s in the case of problems. By encouraging pure functions via propTypes in function components, and Algebraic Effects via Hooks, they&#8217;ve abstracted many of the side effects away from you which is often the causes of many bugs. It still runs on JavaScript so can only help so much. The create-react-app project generator and build system now offers TypeScript to help here.</p>



<p>Redux helps ensure your application only has 1 variable as your data model. You only change it via pure functions which means all data is immutable. This means the data that runs your application is predictable and removes a ton of possibilities for bugs that arise from side effects, race conditions, and mutable state.</p>



<p>Redux is just for synchronous changes, though. Redux Thunks handle all the asynchronous changes you need to make in reasonable to learn Promise style.</p>



<h3 class="wp-block-heading">Elm</h3>



<p>Elm is a typed, functional language that compiles to JavaScript, a framework, has a compiler, and a repl. The elevator pitch for Elm is once your application compiles, you won&#8217;t get null pointer errors. Although I still recommend <a href="https://www.youtube.com/watch?v=EZ05e7EMOLM">Test Driven Development / Red Green Refactor</a>, using the type system, you can refactor with confidence. Simply changing your Model makes the compiler find errors everywhere. Once you fix those and it compiles again&#8230; it works with confidence. It&#8217;s amazing. At first you feel you code Elm 5% of your time, and battle with the compiler 95%. In actuality, that 95% is the best part because once you&#8217;re done, you KNOW YOUR&#8217;RE DONE. As opposed to JS where you go &#8220;Let&#8217;s run it and see&#8230;&#8221;.</p>



<p>The types also help you model your application to ensure it can avoid some logic errors. You can model states that prevent the application from getting in a bad state or an impossible one.</p>



<p>Given that the language is functional, you never have scope problems or other mutable state changing things on you. There are no classes, nor variables, and every function is pure. All changes are immutable and this makes writing unit tests for the hairier parts of your application easier.</p>



<p>Elm does not allow you to create side effects. This further purifies your code making all functions taking inputs and producing outputs. While you can write pure functions in JavaScript, at some point, some function has to do the actual side-effect. The Elm framework handles that.</p>



<p>Like Redux, the Elm framework ensures you only have 1 model, and all changes to it are immutable, and thus predictable. Unlike Redux Thunks, the Elm framework handles both sync and asynchronous changes as normal.</p>



<p>Like React, Elm views are pure functions, taking in data, and returning DOM. Like React,  Elm also doesn&#8217;t care how your do your CSS, although using the <a href="https://github.com/rtfeldman/elm-css">elm-css</a> library can help leverage the type system for it. Like React, Elm doesn&#8217;t care how your organize your code and files.</p>



<p>Like JavaScript, Elm also can have logic errors. Unit tests are still valuable. Property/fuzz tests are still valuable. End to end tests are still valuable. Like JavaScript, Elm can also have race conditions. Elm solves a host of problems JavaScript does not, but you&#8217;ll still have to do work. While you may enjoy your job coding Elm more, it&#8217;s still a job requiring work.</p>



<p>Finally, Elm is an ongoing project. JavaScript has had explosive growth in terms of API&#8217;s implemented in the browser the past decade. Elm purifies them. This means not all API&#8217;s are yet implemented in Elm. As new ones come out, someone has to build those Elm equivalents. Thus, if you&#8217;re doing any Elm app, you&#8217;ll probably still be writing JavaScript. JavaScript doesn&#8217;t go away. How you write that JavaScript, however, is probably much more functional and predictable. Much to the chagrin of many Elm purists, npm/yarn doesn&#8217;t go away. But a ton of problems do!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2019/10/react-redux-thunk-vs-elm.html/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Easier Asynchronous State Modelling in React Redux or Hooks</title>
		<link>https://jessewarden.com/2019/02/easier-asynchronous-state-modelling-in-react-redux-or-hooks.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sun, 17 Feb 2019 19:52:28 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[adt]]></category>
		<category><![CDATA[algebriacdatatype]]></category>
		<category><![CDATA[folktale]]></category>
		<category><![CDATA[hooks]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[react]]></category>
		<category><![CDATA[redux]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5796</guid>

					<description><![CDATA[Introduction Modelling state for asynchronous actions in React using Redux via thunks or sagas is verbose. It requires a lot of code. It also is easy to accidentally miss flipping one of the values and result in a wrong state that your UI then shows the wrong thing. Thankfully there are ways to use Algebraic [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>Modelling state for asynchronous actions in <a href="https://reactjs.org/">React</a> using <a href="https://redux.js.org/">Redux</a> via <a href="https://github.com/reduxjs/redux-thunk">thunks</a> or <a href="https://github.com/redux-saga/redux-saga">sagas</a> is  verbose.  It requires a lot of code. It also is easy to accidentally miss flipping one of the values and result in a wrong state that your UI then shows the wrong thing. Thankfully there are ways to use Algebraic Data Types to model this state that results in less code in your reducers, whether in Redux or Hooks&#8217; <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">useReducer</a>, as well as in your components. Below we&#8217;ll show the 3 problems modelling using Objects can cause and how to solve them using ADT&#8217;s.</p>



<p>All <a href="https://github.com/JesterXL/react-redux-async-types">code shown below is on Github</a>. The <code>master</code>branch has the <code>Object</code> way of modelling, and the <code>types</code> branch has the ADT solutions.</p>



<p>Most of the post below is based on prior art from <a href="https://www.youtube.com/watch?v=IcgmSRJHu_8">Making Impossible States Impossible by Richard Feldman</a>, and <a href="https://www.youtube.com/watch?v=6TDKHGtAxeg">Solving the Boolean Identity Crisis by Jeremy Fairbank</a>. Like Redux, stolen from <a href="https://elm-lang.org/">Elm</a>.</p>



<span id="more-5796"></span>



<h2 class="wp-block-heading">Defining The Problem</h2>



<p>When you load data from a remote data source, most likely from a REST based HTTP server, you&#8217;ll have 3 states: loading, error, and success. This means loading the data, the data failed to load because of an error, and the data successfully loaded.</p>



<h3 class="wp-block-heading">Loading State</h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="583" src="http://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-1024x583.png" alt="" class="wp-image-5798" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-1024x583.png 1024w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-300x171.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1-768x437.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.13-PM-1.png 1441w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption>Loading state</figcaption></figure>



<h3 class="wp-block-heading">Error State</h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="583" src="http://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-1024x583.png" alt="" class="wp-image-5799" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-1024x583.png 1024w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-300x171.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM-768x437.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.47.20-PM.png 1441w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption>Error state</figcaption></figure>



<h3 class="wp-block-heading">Success State</h3>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1024" height="623" src="http://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-1024x623.png" alt="" class="wp-image-5800" srcset="https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-1024x623.png 1024w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-300x183.png 300w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM-768x467.png 768w, https://jessewarden.com/wp-content/uploads/2019/02/Screen-Shot-2019-02-17-at-12.46.57-PM.png 1441w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption>Success state.</figcaption></figure>



<p>To slowly model the above into a <a href="http://jessewarden.com/2012/07/finite-state-machines-in-game-development.html">finite state machine</a>, you start with loading state in your reducer so your component knows &#8220;if loading, show the loading state, else don&#8217;t&#8221;. You default it to <code>true</code>so your UI will be assumed to be waiting to load data.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">true</span>
}</code></span></pre>


<p>When the data loads, you can set the <code>isLoading</code>to <code>false</code> and put your data on the <code>Object</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
  , <span class="hljs-attr">foods</span>: &#91;...]
}</code></span></pre>


<p>However, for errors, you need to indicate that it IS an error, so you add another <code>Boolean</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
  , <span class="hljs-attr">foods</span>: <span class="hljs-literal">undefined</span>
  , <span class="hljs-attr">isError</span>: <span class="hljs-literal">true</span>
}</code></span></pre>


<p>For logging and for the UI, you need to show this <code>Error</code> so you then add it as well:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
  , <span class="hljs-attr">foods</span>: <span class="hljs-literal">undefined</span>
  , <span class="hljs-attr">isError</span>: <span class="hljs-literal">true</span>
  , <span class="hljs-attr">error</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'b00m b00m <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a3.png" alt="💣" class="wp-smiley" style="height: 1em; max-height: 1em;" />'</span>)
}</code></span></pre>


<h3 class="wp-block-heading">Problem #1: Lots of Verbose, Duplicate Code</h3>



<p>Every single asynchronous action in your application has about the same 3 states and 4 properties in an Object to represent it. You then go to represent it in a basic reducer function. When using Redux or <code>useReducer</code>, you use reducer functions, which is the name for the function you put in a <code>reduce</code>function, like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">Array.prototype.reduce</a> or <a href="https://lodash.com/docs/4.17.11#reduce">Lodash&#8217; reduce</a>. Below, &#8220;foods&#8221; is our reducer function:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> foods = <span class="hljs-function">(<span class="hljs-params">state=defaultState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> LOAD_FOODS:
      <span class="hljs-keyword">return</span> {
        ...state
        , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">true</span>
      }
    <span class="hljs-keyword">case</span> LOAD_FOODS_FAILURE:
      <span class="hljs-keyword">return</span> {
        ...state
        , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
        , <span class="hljs-attr">isError</span>: <span class="hljs-literal">true</span>
        , <span class="hljs-attr">error</span>: action.error
      }
    <span class="hljs-keyword">case</span> LOAD_FOODS_SUCCESS:
      <span class="hljs-keyword">return</span> {
        ...state
        , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
        , <span class="hljs-attr">foods</span>: action.foods
  }
}</code></span></pre>


<p>However, either through TDD, manual testing, or unit tests, you start to find out basic problems with your reducer function, and state machines in general: the transitions between states can lead to impossible states&#8230; and your UI freaks out&#8230; or doesn&#8217;t and hides the weirdness.</p>



<p>If we go from loading to error, that&#8217;s fine, our state is:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> state = {
  <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
  , <span class="hljs-attr">foods</span>: <span class="hljs-literal">undefined</span>
  , <span class="hljs-attr">isError</span>: <span class="hljs-literal">true</span>
  , <span class="hljs-attr">error</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(...)
}</code></span></pre>


<h3 class="wp-block-heading">Problem #2: Impossible States</h3>



<p>But if we then retry, we&#8217;ll go from loading to success which results in:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> state = {
  <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
  , <span class="hljs-attr">foods</span>: &#91;...]
  , <span class="hljs-attr">isError</span>: <span class="hljs-literal">true</span>
  , <span class="hljs-attr">error</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(...)
}</code></span></pre>


<p>Wat. How do we have <code>foods</code>and an <code>isError</code> set to true!?</p>



<h3 class="wp-block-heading">Problem #3: Incorrect and Unclear UI Behavior</h3>



<p>You know something&#8217;s wrong when your UI shows an error even though the Network Panel in Chrome shows a status code 200 for the request and the JSON data all looks good:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> FoodsView = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
    useEffect(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
        props.loadFoodsThunk()
    }, &#91;])

    <span class="hljs-keyword">if</span>(props.foods.isLoading) {
        <span class="hljs-keyword">return</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Loading</span> /&gt;</span></span>)
    }
    <span class="hljs-comment">// WHY IS IT STOPPING HERE FOR A SUCCESS!?!<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f620.png" alt="😠" class="wp-smiley" style="height: 1em; max-height: 1em;" /></span>
    <span class="hljs-keyword">if</span>(props.foods.isError) {
        <span class="hljs-keyword">return</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Failed</span> <span class="hljs-attr">error</span>=<span class="hljs-string">{props.foods.error}/</span>&gt;</span></span>)
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FoodsList</span> <span class="hljs-attr">foods</span>=<span class="hljs-string">{props.foods.foods}</span> <span class="hljs-attr">calories</span>=<span class="hljs-string">{props.calories}</span> <span class="hljs-attr">addFood</span>=<span class="hljs-string">{props.addFood}</span> <span class="hljs-attr">removeFood</span>=<span class="hljs-string">{props.removeFood}</span> /&gt;</span></span>
    )
}</code></span></pre>


<p>You realize you need to be super explicit about state transitions to ensure you don&#8217;t accidentally end up in an impossible state like the above where you have a success and error at the same time. We&#8217;ll make our reducer way more verbose to ensure all the unit tests pass:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> foods = <span class="hljs-function">(<span class="hljs-params">state=defaultState, action</span>) =&gt;</span> {
    <span class="hljs-keyword">switch</span>(action.type) {
        <span class="hljs-keyword">case</span> LOAD_FOODS:
            <span class="hljs-keyword">return</span> {
                ...state
                , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">true</span>
                , <span class="hljs-attr">isError</span>: <span class="hljs-literal">false</span>
                , <span class="hljs-attr">error</span>: <span class="hljs-literal">undefined</span>
                , <span class="hljs-attr">foods</span>: <span class="hljs-literal">undefined</span>
            }
        <span class="hljs-keyword">case</span> LOAD_FOODS_FAILURE:
            <span class="hljs-keyword">return</span> {
                ...state
                , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
                , <span class="hljs-attr">isError</span>: <span class="hljs-literal">true</span>
                , <span class="hljs-attr">error</span>: action.error
                , <span class="hljs-attr">foods</span>: <span class="hljs-literal">undefined</span>
            }
        <span class="hljs-keyword">case</span> LOAD_FOODS_SUCCESS:
            <span class="hljs-keyword">return</span> {
                ...state
                , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
                , <span class="hljs-attr">isError</span>: <span class="hljs-literal">false</span>
                , <span class="hljs-attr">error</span>: <span class="hljs-literal">undefined</span>
                , <span class="hljs-attr">foods</span>: action.foods
            }
        <span class="hljs-attr">default</span>:
            <span class="hljs-keyword">return</span> state
    }
}</code></span></pre>


<p>While cool in that it&#8217;s the same pattern, it can be monotonous to duplicate this easily in each of your async reducers that need it without copy pasta. Worse, this is just 3 states. In some cases, especially in Enterprise applications where you&#8217;re dealing with legacy code or services that just go down a lot because of technical debt or high traffic, you could be in an &#8220;unstable&#8221; state, similar to the <a href="https://martinfowler.com/bliki/CircuitBreaker.html">Circuit Breaker Pattern</a>. That&#8217;s ok and expected, but you can start to see how your Object grows, and it&#8217;s not always so obvious what state transition bugs could occur, so you make your reducer even more verbose.</p>



<p>In an Object Oriented (OOP) code base, we&#8217;d just wrap this in a class with methods to ensure safe transitions. This abstraction makes it easier to read and we can test the class in isolation. That won&#8217;t help the UI part above, though.</p>



<p>So what do we do in a Functional Codebase?</p>



<h2 class="wp-block-heading">Solving The Problems</h2>



<p>To prevent the duplicated code, ensure you can&#8217;t reach impossible states in an FP way, and make your UI more clear and easier to debug, we&#8217;ll use an Algebraic Data Type, sometimes called a Tagged Union, provided by <a href="https://folktale.origamitower.com/api/v2.3.0/en/folktale.adt.union.union.union.html">Folktale</a>. There are other libraries you can use for this such as <a href="https://github.com/evilsoft/crocks">Crocs</a> and <a href="https://github.com/sanctuary-js/sanctuary">Sanctuary</a>. If you want to learn more, I have a video <a rel="noreferrer noopener" href="https://www.youtube.com/watch?v=OghJR3BP0Ns" target="_blank">Fun With Folktale</a> which covers the basics at <a rel="noreferrer noopener" href="https://youtu.be/OghJR3BP0Ns?t=1615" target="_blank">26:55</a>.</p>



<p>First, <code>npm install folktale</code> or <code>yarn add folktale</code> and let&#8217;s import it:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">import</span> { union } <span class="hljs-keyword">from</span> <span class="hljs-string">'folktale/adt/union'</span></code></span></pre>


<p>We have a default initial state that looks like:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> defaultState = {
    <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">true</span>
    , <span class="hljs-attr">error</span>: <span class="hljs-literal">undefined</span>
    , <span class="hljs-attr">isError</span>: <span class="hljs-literal">false</span>
    , <span class="hljs-attr">foods</span>: <span class="hljs-literal">undefined</span>
}</code></span></pre>


<p>Let&#8217;s model that same data structure with a type in Folktale:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> FoodsState = union(<span class="hljs-string">'FoodsState'</span>, {
    LoadingFoods() { <span class="hljs-keyword">return</span> {} }
    , FoodsLoaded(foods) { <span class="hljs-keyword">return</span> { foods } }
    , FoodsError(error) { <span class="hljs-keyword">return</span> { error } }
})</code></span></pre>


<p>Instead of 4 un-related, yet related, properties, we can see our 3 states clearly:</p>



<ol class="wp-block-list"><li><strong>LoadingFoods</strong>: loading the food data</li><li><strong>FoodsLoaded</strong>: the list is loaded, and the <code>Array</code> is inside</li><li><strong>FoodsError</strong>: the list failed to load, and the <code>Error</code> is inside </li></ol>



<p>We can leave them in <code>FoodsState</code>, but let&#8217;s destructure them so it&#8217;s less to type:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> { LoadingFoods, FoodsLoaded, FoodsError } = FoodsState</code></span></pre>


<h3 class="wp-block-heading">Solving Problem #2: Many States is Now One State at a Time</h3>



<p>Since there are 3 different Objects, we solve problem #2: You can only be in 1 state at a time. Let&#8217;s update our reducer&#8217;s function signature that has the defaultState:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> foods = <span class="hljs-function">(<span class="hljs-params">state=defaultState, action</span>) =&gt;</span> {</code></span></pre>


<p>To show this:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> foods = <span class="hljs-function">(<span class="hljs-params">state=LoadingFoods(</span>), <span class="hljs-params">action</span>) =&gt;</span> {</code></span></pre>


<p>Way more clear than &#8220;defaultState&#8221; or &#8220;initialState&#8221;; it says exactly right there what state we&#8217;re starting in: Loading. Notice it can&#8217;t magically be <code>FoodsLoaded</code> or <code>FoodsError</code>at the same time like it could in our <code>Object</code>.</p>



<h3 class="wp-block-heading">Solving Problem #1: Verbose Code is Now Less Code</h3>



<p>Let&#8217;s take our massive reducer function switch statement:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> LOAD_FOODS:
        <span class="hljs-keyword">return</span> {
            ...state
            , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">true</span>
            , <span class="hljs-attr">isError</span>: <span class="hljs-literal">false</span>
            , <span class="hljs-attr">error</span>: <span class="hljs-literal">undefined</span>
            , <span class="hljs-attr">foods</span>: <span class="hljs-literal">undefined</span>
        }
    <span class="hljs-keyword">case</span> LOAD_FOODS_FAILURE:
        <span class="hljs-keyword">return</span> {
            ...state
            , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
            , <span class="hljs-attr">isError</span>: <span class="hljs-literal">true</span>
            , <span class="hljs-attr">error</span>: action.error
            , <span class="hljs-attr">foods</span>: <span class="hljs-literal">undefined</span>
        }
    <span class="hljs-keyword">case</span> LOAD_FOODS_SUCCESS:
        <span class="hljs-keyword">return</span> {
            ...state
            , <span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>
            , <span class="hljs-attr">isError</span>: <span class="hljs-literal">false</span>
            , <span class="hljs-attr">error</span>: <span class="hljs-literal">undefined</span>
            , <span class="hljs-attr">foods</span>: action.foods
        }
    <span class="hljs-attr">default</span>:
        <span class="hljs-keyword">return</span> state
}</code></span></pre>


<p>&#8230; and use our union types to write less code AND still ensure only 1 state at a time:</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> LOAD_FOODS:
        <span class="hljs-keyword">return</span> LoadingFoods()
    <span class="hljs-keyword">case</span> LOAD_FOODS_FAILURE:
        <span class="hljs-keyword">return</span> FoodsError(action.error)
    <span class="hljs-keyword">case</span> LOAD_FOODS_SUCCESS:
        <span class="hljs-keyword">return</span> FoodsLoaded(action.foods)
    <span class="hljs-keyword">default</span>:
        <span class="hljs-keyword">return</span> state
}</code></span></pre>


<p>Who&#8217;s your buddy? WHO&#8217;S YOUR BUDDY!?</p>



<p>If the <code>action.type</code>is loading, cool, we&#8217;re loading. If the type is failure, we return a failed type and put the error in side. Lastly, if we&#8217;re successful, we return a success with our data inside. 28 lines to 10.</p>



<h3 class="wp-block-heading">Solving Problem #3: Unclear UI Showing Wrong State to More Clear, Deterministic, and Easier to Debug</h3>



<p>Lastly, our UI can more clearly represent this state. Instead of the imperative, abort early and render based on our guess at what the <code>Object</code> means:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> FoodsView = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
    useEffect(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
        props.loadFoodsThunk()
    }, &#91;])

    <span class="hljs-keyword">if</span>(props.foods.isLoading) {
        <span class="hljs-keyword">return</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Loading</span> /&gt;</span></span>)
    }
    
    <span class="hljs-keyword">if</span>(props.foods.isError) {
        <span class="hljs-keyword">return</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Failed</span> <span class="hljs-attr">error</span>=<span class="hljs-string">{props.foods.error}/</span>&gt;</span></span>)
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FoodsList</span> <span class="hljs-attr">foods</span>=<span class="hljs-string">{props.foods.foods}</span> <span class="hljs-attr">calories</span>=<span class="hljs-string">{props.calories}</span> <span class="hljs-attr">addFood</span>=<span class="hljs-string">{props.addFood}</span> <span class="hljs-attr">removeFood</span>=<span class="hljs-string">{props.removeFood}</span> /&gt;</span></span>
    )
}</code></span></pre>


<p>We can instead run a pure function against the type using <code>matchWith</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> FoodsView = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
    useEffect(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
        props.loadFoodsThunk()
    }, &#91;])

    <span class="hljs-keyword">return</span> props.foods.matchWith({
        <span class="hljs-attr">LoadingFoods</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span>
            (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Loading</span> /&gt;</span></span>)
        , <span class="hljs-attr">FoodsError</span>: <span class="hljs-function">(<span class="hljs-params">{ error }</span>) =&gt;</span>
            (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Failed</span> <span class="hljs-attr">error</span>=<span class="hljs-string">{error}</span> /&gt;</span></span>)
        , <span class="hljs-attr">FoodsLoaded</span>: <span class="hljs-function">(<span class="hljs-params">{ foods }</span>) =&gt;</span>
            (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FoodsList</span> <span class="hljs-attr">foods</span>=<span class="hljs-string">{foods}</span> <span class="hljs-attr">calories</span>=<span class="hljs-string">{props.calories}</span> <span class="hljs-attr">addFood</span>=<span class="hljs-string">{props.addFood}</span> <span class="hljs-attr">removeFood</span>=<span class="hljs-string">{props.removeFood}</span> /&gt;</span></span>)
    })
}</code></span></pre>


<p>No need to inspect different <code>Booleans</code>and guess you did it in the right order, or have things break even if you did, you now have VERY clearly named states to match against using a pure function.</p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>Modelling asynchronous data in Redux or the <code>useReducer</code> React Hook can  result in states that are impossible, yet your UI goes there by accident. This results in verbose reducers that are a pain to maintain as the amount of <code>fetch</code> calls in your application grows. Unless you have good tests, it also will sometimes result in UI bugs if you accidentally don&#8217;t model a state just right with all the <code>Boolean</code> flags set to the correct values.</p>



<p>Using ADT&#8217;s, or tagged unions, we can ensure impossible states are impossible to get to, we can significantly reduce how much reducer code we write, and our UI render code becomes more clear, testable, and debuggable.</p>



<h3 class="wp-block-heading">Et tu, Action Creators?</h3>



<p>And before you ask, sadly no, you cannot use them for Action Creators. Redux and various Redux libraries expect Action Creators to be pure Objects, and the <code>type</code> property to a <code>String</code>. I suppose you could create your own middleware, thus drastically reducing your reducer size and they&#8217;d become map functions vs. reducer functions. But at that point, you&#8217;re better off using Elm, heh!</p>



<h3 class="wp-block-heading">Can Strong Typing Help Here?</h3>



<p>On that note, be aware that TypeScript and Flow, currently, cannot detect if you&#8217;ve handled all match cases. For example, if you do this in your UI:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">return</span> props.foods.matchWith({
    <span class="hljs-attr">LoadingFoods</span>: <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span>
        (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Loading</span> /&gt;</span></span>)
    , <span class="hljs-attr">FoodsError</span>: <span class="hljs-function">(<span class="hljs-params">{ error }</span>) =&gt;</span>
        (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Failed</span> <span class="hljs-attr">error</span>=<span class="hljs-string">{error}</span> /&gt;</span></span>)
    , <span class="hljs-attr">FoodsLoaed</span>: <span class="hljs-function">(<span class="hljs-params">{ foods }</span>) =&gt;</span>
        (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FoodsList</span> <span class="hljs-attr">foods</span>=<span class="hljs-string">{foods}</span> <span class="hljs-attr">calories</span>=<span class="hljs-string">{props.calories}</span> <span class="hljs-attr">addFood</span>=<span class="hljs-string">{props.addFood}</span> <span class="hljs-attr">removeFood</span>=<span class="hljs-string">{props.removeFood}</span> /&gt;</span></span>)
})</code></span></pre>


<p>Notice we misspelled <code>FoodsLoaded</code>to <code>FoodsLoaed</code>. The compiler in Elm would catch that and not compile, but <a href="https://www.typescriptlang.org/">TypeScript</a> and <a href="https://flow.org/">Flow</a> will not. This will result in a runtime exception. The <a href="https://github.com/tc39/proposal-pattern-matching">pattern matching proposal for JavaScript</a> is at Stage 1 at the time of this writing so until that solidifies, if you&#8217;re a TypeScript fan, they have <a href="https://pattern-matching-with-typescript.alabor.me/">better ways of doing pattern matching the TypeScript way</a> which&#8217;ll give you ADT&#8217;s + strong typing guarantees. It&#8217;s too verbose for my taste, though.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
