<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Jewell on Medium]]></title>
        <description><![CDATA[Stories by Michael Jewell on Medium]]></description>
        <link>https://medium.com/@mjewell?source=rss-2cf8709f7781------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Michael Jewell on Medium</title>
            <link>https://medium.com/@mjewell?source=rss-2cf8709f7781------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 12:47:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mjewell/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hacking Cypress Return Values For Better E2E Tests]]></title>
            <link>https://medium.com/@mjewell/hacking-cypress-return-values-for-better-e2e-tests-767cb09b1a03?source=rss-2cf8709f7781------2</link>
            <guid isPermaLink="false">https://medium.com/p/767cb09b1a03</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael Jewell]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 15:34:14 GMT</pubDate>
            <atom:updated>2023-12-13T15:34:14.815Z</atom:updated>
            <content:encoded><![CDATA[<p>In the dynamic world of software testing, Cypress has emerged as a go-to framework for end-to-end testing thanks to its robustness and ease of use. One big challenge developers face with Cypress is <a href="https://learn.cypress.io/advanced-cypress-concepts/database-initialization-and-seeding">managing database state initialization</a> through API calls in a way that mimics the simplicity and clarity of synchronous operations. Cypress’ asynchronous nature can make such tasks seem daunting, often leading to convoluted code structures.</p><p>This blog post introduces a new technique to address this issue. It allows you to interact with your API in a manner that appears synchronous, enabling straightforward assignment to variables — a feat not typically achievable with Cypress’ asynchronous behavior. This approach not only simplifies your testing process but also enhances readability and maintainability of your test scripts, paving the way for more efficient and effective end-to-end testing.</p><h3>How Cypress Runs Your Test</h3><p>When learning cypress, you might be surprised to find that while your test code looks synchronous, everything is actually happening asynchronously behind the scenes. <a href="https://docs.cypress.io/guides/core-concepts/introduction-to-cypress#The-Cypress-Command-Queue">Every command in cypress is pushing a command into a queue that will be executed later.</a> You can think of Cypress as operating in alternating phases of queueing commands, and then executing them. In the example below, you can see how using cy.then causes our code to be <strong>evaluated</strong> <strong>out of order</strong> (based on the counter value), even though the commands are still <strong>executed in order</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeId5i-d8CNbAfJVcyc5ZA.png" /></figure><p>This unique behavior is what sets Cypress apart, enabling it to reduce flake in the highly mutable environment it runs in. However, this approach isn’t without its challenges.</p><p>For example, one major limitation is that <a href="https://docs.cypress.io/guides/core-concepts/variables-and-aliases#Return-Values">you can’t assign return values to variables</a> because the code returning the value won’t be executed immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*49CjsK7gYMlA7zGc7lsTLA.png" /></figure><p>Cypress provides <a href="https://docs.cypress.io/guides/core-concepts/variables-and-aliases#Aliases">a few workarounds</a> for this limitation that work well in most cases, but it can lead to a poor developer experience when commands rely on each other a lot.</p><h3>Example Problem</h3><p>Let’s pretend we’re testing a basic blogging platform, and as part of our test setup we want to create a comment on a post. To do that, we need to create:</p><ul><li>a user to author the post</li><li>a post</li><li>a user to author the comment</li><li>a comment on the post</li></ul><p>With regular cypress code that would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e99e643f54c4e97653a8b04b10a7f03c/href">https://medium.com/media/e99e643f54c4e97653a8b04b10a7f03c/href</a></iframe><p>It’s pretty hard to read (and write), even for this relatively simple example. In an ideal world we would be able to write the code more like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/defcf22401062d48091584d6f47759a0/href">https://medium.com/media/defcf22401062d48091584d6f47759a0/href</a></iframe><p>But with everything happening asynchronously, we can’t use this simple variable assignment style to avoid all the nesting.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT5LMui3MlVE9dpjX2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT5LMui3MlVE9dpjX2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxT5LMui3MlVE9dpjX2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="331" frameborder="0" scrolling="no"><a href="https://medium.com/media/128b961e94ee70e81043a87cdc92f56c/href">https://medium.com/media/128b961e94ee70e81043a87cdc92f56c/href</a></iframe><h3><strong>First Attempt</strong></h3><p>We can get a pretty close to our desired code by relying on a few tricks:</p><ol><li>We can return an object synchronously, and then asynchronously update an internal property later to point to the response object. Going forward, we’ll call this object a container.</li><li>We can use proxies to make this container transparent to the developer by forwarding reads to the response object it holds.</li><li>We can make cypress wait for our previous request to resolve (and our container to be updated) by using cy.then.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edd767e92bb06b4c3db978201e594ec0/href">https://medium.com/media/edd767e92bb06b4c3db978201e594ec0/href</a></iframe><p>The resulting code is still pretty convoluted, but it has a few nice properties.</p><ol><li>We can use regular variable assignment.</li><li>We can easily add types to our variables.</li><li>We always just wrap with one level of cy.then, regardless of what other requests need to wait for.</li></ol><p>Because of the consistency we introduced in point 3, we can abstract it behind a function and simplify the test code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4abb7eaf3d8293b37283af818c1eed/href">https://medium.com/media/3d4abb7eaf3d8293b37283af818c1eed/href</a></iframe><p>Our test case is starting to look pretty nice and readable, but there’s a small difference. In order for the above to work, we needed to change the body of the request to be a callback instead of just passing an object. This is because we need it to be evaluated once the previous requests have resolved (in the cy.then).</p><p>Another limitation to this approach is that you need to create your objects in separate commands because we need to wait for the previous one to finish before proceeding. In the example above, if we don’t need a reference to the comment author variable, it would be nice if we could inline that into the comment creation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49793246d85b1aec65007de4917d2f6d/href">https://medium.com/media/49793246d85b1aec65007de4917d2f6d/href</a></iframe><p>But this won’t work. Our user request won’t be finished by the time we ask for the id so we end up throwing an error.</p><h3>Second Attempt</h3><p>In order to get around these limitations, we need to remove the arrow functions. The reason we added the arrow function was to delay reading the previous responses until after they were resolved, but maybe we can rely on our old trick to get around this too — we can create containers for our future values and then extract the value from the containers when we actually we make the request.</p><p>This new version of the proxy recursively creates new containers for every property you access, and then when you eventually set the value at the top level it recursively updates all the subcontainers too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60ff76121e2ac9437492facb61e1bb77/href">https://medium.com/media/60ff76121e2ac9437492facb61e1bb77/href</a></iframe><p>Using this new container, we don’t need the arrow functions anymore. Let’s step through what part of the state of our test looks like as it runs.</p><p>When we initially evaluate the comment request body it looks like this:</p><pre>{<br>  text: &quot;My first comment&quot;,<br>  userId: { _ref: null },<br>  postId: { _ref: null },<br>}</pre><p>But when we actually make the comment request (inside the cy.then) the previous requests have finished, and the proxy will have updated the values in the containers:</p><pre>{<br>  text: &quot;My first comment&quot;,<br>  userId: { _ref: 2 },<br>  postId: { _ref: 123 },<br>}</pre><p>So all we need to do is strip the _ref objects out, leaving us with just the desired result:</p><pre>{<br>  text: &quot;My first comment&quot;,<br>  userId: 2,<br>  postId: 123,<br>}</pre><p>Here’s what the code looks like to get all that working. We have a function to recursively search for properties called _ref and remove the containers, and we call that function inside our request function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0bfb073c557443f4662fc7919c62b20/href">https://medium.com/media/d0bfb073c557443f4662fc7919c62b20/href</a></iframe><p>And with that, our original desired test code works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/489a71aa05311227d8ace92ec0c0e309/href">https://medium.com/media/489a71aa05311227d8ace92ec0c0e309/href</a></iframe><h4>Hidden Features</h4><p>With this magical proxy behavior, we get two other nice features.</p><ol><li>We can inline requests into other requests because we don’t have to wait for them to finish anymore.</li><li>We can do deep property accesses on requests that haven’t finished yet because our proxy can create layers of containers to any depth.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a028a7248a1a2049d09eced0900a8d6/href">https://medium.com/media/8a028a7248a1a2049d09eced0900a8d6/href</a></iframe><h3>What’s Next?</h3><p>By leveraging this approach, you can write clearer, more maintainable tests, significantly enhancing your end-to-end testing strategy. Stay tuned for a follow-up blog post where we’ll dive deeper with practical guidance and additional insights on how to effectively implement this technique, along with other strategies, to elevate your testing game in Cypress.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=767cb09b1a03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rethinking React State]]></title>
            <link>https://medium.com/@mjewell/rethinking-containers-and-presenters-82aa1a8a5a72?source=rss-2cf8709f7781------2</link>
            <guid isPermaLink="false">https://medium.com/p/82aa1a8a5a72</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mobx]]></category>
            <dc:creator><![CDATA[Michael Jewell]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 03:58:58 GMT</pubDate>
            <atom:updated>2019-01-29T17:19:01.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Eventually some of your React components will get too complicated to easily maintain. When they do, it can be helpful to split them up into smaller parts. To figure out the right way to do this, we first need to think about what a React component is made of.</p><h3>Anatomy of a React Component</h3><p>From the outside, a React component is a black box. You don’t need to know how it’s implemented internally, you just know that it takes some props in and outputs some UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pPPY5Y-EWDb9mOp3IaUcA.png" /></figure><p>When you take a look at the inside though, a component is made of 3 parts. There’s the logic that determines its behavior (the brain), the lifecycle (the heart) and the rendering (the palette).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8mYQLxY2xCF1GcFmiynbQ.png" /></figure><h3>Anatomy of Containers and Presenters</h3><p>A common pattern is to split your component into containers (behavior) and presenters (rendering). The lifecycle could exist in either component depending on how you decide to implement it. For this example, we will put it together with the rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4RxpnZ5W2xw3Xvrj2zvbw.png" /></figure><p>This right side of this split works well. React is great for handling rendering and DOM lifecycle. The left side, on the other hand, has some problems. React has a mechanism for handling state, but it’s not ideal. There are 3 key issues with using React for your logic:</p><ol><li>Testing is harder because you have to deal with rendering the component</li><li>The logic and state is coupled to React</li><li>It’s hard to make the state accessible outside of the component</li></ol><h3>React + Stores</h3><p>If we could write our logic outside of React, we could solve all of these problems. We just need to put our logic into a regular javascript class, and reference it from our component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gf5GP3jD-QZGQWNr88tdVg.png" /></figure><p>With this structure the first component is completely empty, just referencing the store, so we can just remove it entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNhFv8xs7F5aC7tlVJkfJg.png" /></figure><p>This is what we ultimately want, but it’s not quite so simple to achieve it. For our store to work, we need to know what parts of React the brain relies on. There are 2 core React concepts that are relevant to the brain: props and state. Specifically, here’s what we need from our store:</p><ol><li>State changes cause the component to be rerendered</li><li>Props provided to the component are available to the store</li><li>The store can know when props change</li></ol><p>If we use mobx for our state we can achieve the first goal. We also get to avoid the use of setState and all of its <a href="https://blog.cloudboost.io/3-reasons-why-i-stopped-using-react-setstate-ab73fc67a42e">associated problems</a>. To get access to the props we will need our store to have a reference to the component. Once we have that reference we can easily read the props from it. We can also use mobx to know when the props change. As long as our component is marked as an observer, which is required for our state changes to cause rerenders, the props will also be made observable, meaning we could use mobx reactions to respond to changes in props.</p><h3>Store Improvements</h3><p>Ideally, the store should also be able to be created without an associated component. A lot of the time we have logic in our app that is not connected to some particular part of the UI. We may even have cases where we don’t have access to the component until after the store is created. An example might be if we want to create a store and pass it to a component as a prop so we can read its state from other components too. In this case the component needs to be able to associate itself with the store after the fact.</p><p>We also may want to configure our stores somehow. React components handle this well by taking in a single object containing key value pairs. We can use the same pattern for our stores. Our new interface for our stores becomes something like this: new Store(props, component). Since now we can receive props through the constructor and through the associated component our store should see its props as the combination of these two.</p><h3>Show Me The Code</h3><p><a href="https://github.com/mjewell/mobx-base-store">mobx-base-store</a> is a small library that defines a class that you can extend to gain this functionality, as well as some other nice features like propTypes and defaultProps.</p><p>To demo it, we’ll use a simple example: a component that fetches some data from an api, does some manipulation of the data, and renders it. We’ll start with the store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1e02d7d1eb29e65ffd1ea96338aa2d1/href">https://medium.com/media/b1e02d7d1eb29e65ffd1ea96338aa2d1/href</a></iframe><p>As you can see, this store has no connection to React. A javascript developer with no React experience at all could implement it. It defines all of the behavior of our component, but nothing about how it looks. We could theoretically even write our component with some other UI framework without having to make any changes to this part of the code.</p><p>We avoided the use of setState entirely. Manipulating state in the store is as simple as doing a regular assignment operation, and the state changes happen synchronously, potentially reducing bugs. If you’re using mobx already, this is nothing new.</p><p>We have access to any configuration (the fetch method) through this.props, just like a regular React component. At this point, exactly where those props come from is not important.</p><p>We can also easily test the store without any ceremony around rendering. Notice that we do not need any other libraries like enzyme to write our tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/188f79b1c26fd955f9940634b1895ccf/href">https://medium.com/media/188f79b1c26fd955f9940634b1895ccf/href</a></iframe><p>Finally, to connect the store up to a component we just add a constructor that creates the store, and then we can use it in componentDidMount and render. We use React for the rendering and lifecycle hooks, but remove all of our logic from it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f03cbed5e7b6bcf72068694c40e1803d/href">https://medium.com/media/f03cbed5e7b6bcf72068694c40e1803d/href</a></iframe><p>In this case, we instantiate the store by calling Store.create(null, this). This means that we are not providing any props to the store explicitly, but it will receive all the props that this component receives. If we wanted to have access to the store in another component, we could easily instantiate the store elsewhere and pass it to the component as a prop.</p><p>That’s all. We’ve managed to extract the brain of our component out into a store that is completely distinct from React and hook everything together so our component behaves as expected. Here’s a link to the code sandbox if you want to try it out: <a href="https://codesandbox.io/s/7zk0p0jz66">https://codesandbox.io/s/7zk0p0jz66</a></p><h3>Summary</h3><p>In my experience, this approach results in much cleaner code than the current recommended approaches. Without doing anything drastically different from a code perspective we have massively improved the testability of our component and reduced our coupling to React.</p><p>If you are already using mobx (which I highly recommend) you shouldn’t have to change much about how you write your components. In fact, for most components you should just be able to copy/paste everything over since stores maintain the props interface you’re already using. Maintaining this interface keeps the learning curve of using this technique extremely low.</p><p>There’s several other scenarios that mobx-base-store can handle, but we’ll save those for another post. Let me know in the comments if you have any comments or suggestions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82aa1a8a5a72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Page Mobx]]></title>
            <link>https://medium.com/@mjewell/multi-page-mobx-a5c6bff7cc54?source=rss-2cf8709f7781------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c6bff7cc54</guid>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobx]]></category>
            <dc:creator><![CDATA[Michael Jewell]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 13:01:20 GMT</pubDate>
            <atom:updated>2018-07-02T13:01:20.895Z</atom:updated>
            <content:encoded><![CDATA[<p>Mobx is very unopinionated about how you structure your app, which is ultimately a great thing, but it can be intimidating when you are building something bigger. There are some recommendations but they don’t go into much detail beyond simply separating out UI related logic from business logic. As your UI grows you’ll probably want to figure out a more structured approach. Here’s what I’ve found to work best.</p><h4>App Store</h4><p>This is where all the business logic for your app goes. How you structure this is up to you. This store should be completely decoupled from the UI to the point where if you were to rewrite your app using some other framework, or to write it as a mobile app, you could reuse this with no changes. Typically this will include things like API calls or state that is independent of the UI, like information about the logged in user.</p><h4>UI Stores</h4><p>Let’s say you’re building YouTube. As of today, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7rE5ZdD-V3a-WReWr25wg.png" /></figure><p>The page has a header bar, a sidebar navigation menu, and an area for the current page content. All of these will have some kind of logic and state associated with them that we want to put into stores, but figuring out how these stores should be organized can be hard.</p><p>When you navigate through the app, the header and nav stay constant and the current page content updates. As a result, the header and nav shouldn’t depend on anything about the current page, since it can change. On the other hand, the page can know that it will be rendered into the layout, so the stores for the page can know about the stores for the header and nav. Similarly, all of the stores can know that they are part of the app, and should have access to the app store. In this case, we might build our UI stores like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LnAB4Omw0Z2FnJp8wxoMQ.png" /></figure><p>Each of the stores in the left column is responsible for coordinating access between their respective stores on the right. The stores on the right are responsible for the actual behavior of your UI and will contain most of your logic.</p><p>As the user navigates through the app, the current page store will be destroyed and replaced with an instance corresponding to the new page. To get a better idea of how this is implemented, let’s look at how the page store gets created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e4fe7b2d061524da582490bcbf1b8df/href">https://medium.com/media/0e4fe7b2d061524da582490bcbf1b8df/href</a></iframe><p>When our page component is rendered, it creates it’s own store and puts it into a provider so that anything below it can access it. We also inject all the stores from any providers above and pass them to the constructor for the page store. The page store itself will then create any stores that are needed by the page and is responsible for providing any dependencies to them. When the user navigates, this component is unmounted (by whichever routing library you use), and a new page is mounted, creating a new page store. In this case, our page store might look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fa79c634aad3e93dbf6397f1bd7e767/href">https://medium.com/media/0fa79c634aad3e93dbf6397f1bd7e767/href</a></iframe><p>The page store instantiates the other stores by passing in a callback which generates the props that those stores need. This allows us to reuse these stores in other contexts, and using a callback means these props can be reactive to changes. In this case, the VideosStore gets access to the videos index api, but the VideosStore itself doesn’t have to know about the implementation, making it easy to test. Since all of our stores will need to handle the props coming in as a function, let’s make a base class for our stores that can handle this behavior for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e6f9052f72ba23b62b4ef8fe056860e/href">https://medium.com/media/1e6f9052f72ba23b62b4ef8fe056860e/href</a></iframe><p>Now we can create our VideosStore by subclassing the BaseStore and accessing getVideos through this.props, just like a React component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06d4730e607577e6b96cc8bb3cd196b0/href">https://medium.com/media/06d4730e607577e6b96cc8bb3cd196b0/href</a></iframe><h4>Accessing Props from Components</h4><p>Sometimes our stores correspond 1:1 with a component on the page, and need access to props from that component that are not available in the store. For example, if our page url was parameterized, like /videos/:videoId, our page store would need access to this videoId to know which content to load. This information should be provided as a prop to your component by your routing library. In this case, we want be able to access the component props in the store. We can update our BaseStore to include this functionality:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b467d3f92741544fee2d8ce0371cffb5/href">https://medium.com/media/b467d3f92741544fee2d8ce0371cffb5/href</a></iframe><p>Using this new BaseStore, our component can bind itself to the store by calling this.state.store.bindComponent(this) and the store will then have access to the combined props through this.props. Any props coming from the component will override the props passed in to the store directly. This behavior is similar to that of inject from mobx-react.</p><p>In this case, our stores formed 3 layers: the app store; the layout store; and the page store. In your case, it may make sense to have more or less. Typically whenever you are using a router to determine what to render, that will constitute a new layer of stores. Grouping your stores into layers helps to avoid dependencies on stores which may not behave as expected, or even exist.</p><p>By having a parent store at each layer that is responsible for setting up all the other stores, we can make those stores easier to test and reuse. All the UI stores expect to work with a plain props object, just like a React component, while the parent store is responsible for deciding what these props actually correspond to. Since the parent store has relatively little logic in it, we can reduce the amount of testing that needs to be done there and focus more on unit testing the individual parts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c6bff7cc54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pulling State out of React]]></title>
            <link>https://medium.com/@mjewell/pulling-state-out-of-react-e01fa218bda3?source=rss-2cf8709f7781------2</link>
            <guid isPermaLink="false">https://medium.com/p/e01fa218bda3</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[Michael Jewell]]></dc:creator>
            <pubDate>Fri, 06 Apr 2018 11:31:01 GMT</pubDate>
            <atom:updated>2018-04-11T21:31:54.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tio2VdylSA7QR9qh." /><figcaption>Photo by <a href="https://unsplash.com/@clemhlrdt?utm_source=medium&amp;utm_medium=referral">Clément H</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A pretty common pattern in React is to use container and presenter components. Dan Abramov talks about it <a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">here</a>, but the gist of it is that you want to separate how the component works from how it looks. To do this, you create two components, a presenter and a container. The presenter is typically a simple stateless functional component, and the container contains all the lifecycle methods and state that determine how the component will behave.</p><p>Typically, the containers render function looks something like this:</p><pre>render() {<br>  return &lt;WrappedComponent {...this.props} {...this.state} /&gt;<br>}</pre><p>Basically, it does very little. The point of the container isn’t to render anything. In fact, it shouldn’t even know about rendering at all. Ultimately, our business logic has nothing to do with React. All containers care about is that the right things happen when the user asks, not how the user asks. It would be great if our container could just be a plain Javascript object.</p><p>Let’s see if we can make it work with a simple classic example, a counter:</p><p>We have a basic presenter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7920cf7add9f5e550af7ae3453f1e81/href">https://medium.com/media/f7920cf7add9f5e550af7ae3453f1e81/href</a></iframe><p>And a javascript object that represents a counter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c481ee2cc14708bee7bb0c386d48594a/href">https://medium.com/media/c481ee2cc14708bee7bb0c386d48594a/href</a></iframe><p>Let’s make a higher-order component which takes a store and a component and returns a new component with the relevant parts of the store being passed in as props:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6532fbfcf726d952a93b7f05b8fe4e1b/href">https://medium.com/media/6532fbfcf726d952a93b7f05b8fe4e1b/href</a></iframe><p>And hook it all together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7fb634a722ed6a2d6dcb8f902cf3646/href">https://medium.com/media/c7fb634a722ed6a2d6dcb8f902cf3646/href</a></iframe><p>This example exists in the V1 directory in <a href="https://codesandbox.io/s/n52zxjym8p">this code sandbox</a>.</p><p>Ok, so our state gets into the presenter (the counter is set to 0), but pretty quickly you’ll find out that the buttons don’t work. Technically they do increment and decrement the counter, but the presenter isn’t re-rendering so it looks like nothing is happening. Let’s make it so our store gets a callback that allows it say when its state has changed, allowing anyone who cares about the new state to have an opportunity to grab it. We could write it like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6174d9074d399008496d90023b6a35db/href">https://medium.com/media/6174d9074d399008496d90023b6a35db/href</a></iframe><p>So now the store can tell us when things have changed, we need to get our component to re-render when that happens. And how do you make a component re-render in React? You call setState. Let’s update our createCounterContainer function to allow the store to tell us when to re-render:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30278140eb0e7749357177ad47b7095b/href">https://medium.com/media/30278140eb0e7749357177ad47b7095b/href</a></iframe><p>And connecting these together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d7599a6417e00daf9964886fceb634e/href">https://medium.com/media/9d7599a6417e00daf9964886fceb634e/href</a></iframe><p>This example exists in the V2 directory in <a href="https://codesandbox.io/s/n52zxjym8p">this code sandbox</a>.</p><p>Things seem to be working! We can now use a plain javascript object to represent the state and logic of our app. Unfortunately, our createCounterContainer function is specific to our counter store because it has to know what props to pass through. It sucks for us to have to rewrite this container function every time, so what if we make it more general.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2cb61d2cb21a950f71db5b2f70e691f/href">https://medium.com/media/f2cb61d2cb21a950f71db5b2f70e691f/href</a></iframe><p>Now we take a second argument to our createContainer function which tells us how to turn our store into the props that our presenter expects. In this case, this function is pretty simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/999aa0e20f39877dc1fb1393d7c18a79/href">https://medium.com/media/999aa0e20f39877dc1fb1393d7c18a79/href</a></iframe><p>And finally, putting them together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34718e773bd998fc2f27db5a4197ccb8/href">https://medium.com/media/34718e773bd998fc2f27db5a4197ccb8/href</a></iframe><p>This example exists in the V3 directory in <a href="https://codesandbox.io/s/n52zxjym8p">this code sandbox</a>.</p><p>Now we have a reusable function for creating container components! It’s really nice that we can write our store without it having to know anything about React, but it still sucks that the store has to manually tell you when things change. That could definitely result in some pretty annoying bugs. It would be great if there was a way that our app could just magically know when state has changed…</p><p>Guess what? There’s a library for that! <a href="https://github.com/mobxjs/mobx">Mobx</a> (and <a href="https://github.com/mobxjs/mobx-react">mobx-react</a>).</p><p>Mobx efficiently keeps track of your state and can seamlessly handle the notifying of updates. Even better, it does it optimally, only triggering re-renders when they are strictly necessary. What does our store look like with mobx?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55ae9275ad3507bf9166debbd7741904/href">https://medium.com/media/55ae9275ad3507bf9166debbd7741904/href</a></iframe><p>Pretty much exactly what we started with originally, but we let it know that the value is observable. Then we make sure our container component is marked as an observer, allowing us to remove the update triggering logic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be94c0d611302f850ecaa377e64855cc/href">https://medium.com/media/be94c0d611302f850ecaa377e64855cc/href</a></iframe><p>Finally, using our latest createContainer function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79b380fe41c7aba96607ba28a68c125f/href">https://medium.com/media/79b380fe41c7aba96607ba28a68c125f/href</a></iframe><p>And that’s it, nothing else changes. This final example exists in the mobx directory in <a href="https://codesandbox.io/s/n52zxjym8p">this code sandbox</a>.</p><p>Now the business logic is isolated into plain javascript objects and we don’t even have to think about how or when rendering happens. This gives us a couple of big advantages:</p><ol><li>The stores are easy to understand because there is no react boilerplate.</li><li>Testing is easier because you don’t have to worry about rendering that isn’t actually relevant to the tests.</li></ol><p>Check out a live demo of these 4 versions of the code here and let me know what you think of this approach:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fn52zxjym8p&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fn52zxjym8p&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fn52zxjym8p%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/c50bbe4bb5cfcab8be8c147a0c4416b7/href">https://medium.com/media/c50bbe4bb5cfcab8be8c147a0c4416b7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e01fa218bda3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing Higher-Order Component Reusability]]></title>
            <link>https://medium.com/@mjewell/maximizing-higher-order-component-reusability-289950410b83?source=rss-2cf8709f7781------2</link>
            <guid isPermaLink="false">https://medium.com/p/289950410b83</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[higher-order-components]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Michael Jewell]]></dc:creator>
            <pubDate>Thu, 02 Nov 2017 07:25:52 GMT</pubDate>
            <atom:updated>2017-11-02T07:27:13.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8d-4wYLN9wwiEsLAA_5yg.jpeg" /></figure><p>Much like regular React components are the core unit for sharing UI elements in an app, higher-order components are the core unit for sharing behavior. For example, let’s say a lot of your components load data from the server and while you’re waiting for a response you want to render a loading indicator. You might write a higher-order component like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db41a8e966eaf0942af0d1e4eaa1396e/href">https://medium.com/media/db41a8e966eaf0942af0d1e4eaa1396e/href</a></iframe><p>But then let’s say we want to be able to configure the loading indicator to be different for different components. The typical way to do this is to wrap it with another function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c8bdec02c8fa3487f3ce34d3ba859c2/href">https://medium.com/media/1c8bdec02c8fa3487f3ce34d3ba859c2/href</a></iframe><p>Looks great, but maybe now we want to be able to configure something else too, like the name of the loading prop. If we want to add a new parameter we have a few options for our function signature:</p><ol><li>(LoadingComponent, loadingPropName) =&gt; WrappedComponent =&gt; props</li><li>({ LoadingComponent, loadingPropName }) =&gt; WrappedComponent =&gt; props</li><li>LoadingComponent =&gt; loadingPropName =&gt; WrappedComponent =&gt; props</li></ol><p>In cases 1 and 2, we are required to provide both the LoadingComponent and the loadingPropName param together. Using option 3, we can provide the LoadingComponent first, and provide the propName later. This partial application from option 3 allows us to create even more reusable functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d103e562c1645667927343e2a095934c/href">https://medium.com/media/d103e562c1645667927343e2a095934c/href</a></iframe><p>It’s pretty nice, but maybe we want to provide just the loadingPropName, and have someone else provide the LoadingComponent later. Using this method, there’s no way to invert this order without manually creating a new function:</p><pre>loadingPropName =&gt; LoadingComponent =&gt; withLoadingIndicator(LoadingComponent)(loadingPropName)</pre><p>This kinda sucks, and it gets much more complicated when the number of configuration options increases. Unfortunately, the number of configuration options isn’t necessarily small, and there isn’t normally any obvious way to order the params to cover all your use cases.</p><h4>Configurable Function</h4><p>To fix this problem, I wrote a tiny library called <a href="https://github.com/mjewell/configurable-function">configurable-function</a>. This library essentially creates a curried version of a function where you can provide the arguments in whatever order you want. This allows us to rewrite the previous example like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/476a531843da1871f3f6768cd4cf5341/href">https://medium.com/media/476a531843da1871f3f6768cd4cf5341/href</a></iframe><p>As shown above, using this library we can create partially applied versions of our original higher-order component with any individual params locked down, making the component as reusable as possible without having to make any difficult design decisions about param ordering at the start. Additionally, by enforcing named parameters we guarantee that as new configuration options are added the function will always have a backward compatible signature so you can extend your HOCs freely.</p><p>Have you faced similar issues when using higher-order components? Let me know what you think of this approach. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=289950410b83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Composition of React Components]]></title>
            <link>https://medium.com/@mjewell/functional-composition-of-react-components-527f6930a42?source=rss-2cf8709f7781------2</link>
            <guid isPermaLink="false">https://medium.com/p/527f6930a42</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Michael Jewell]]></dc:creator>
            <pubDate>Tue, 28 Mar 2017 03:04:23 GMT</pubDate>
            <atom:updated>2018-01-08T15:31:36.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Functional composition is a mechanism to build complex functions by combining multiple simpler functions. This style can help you create more reusable functions in your code, reducing duplication, testing, and bugs.</p><p>A great example of designing for functional composition is the <a href="https://github.com/lodash/lodash/wiki/FP-Guide">lodash/fp</a> library. lodash/fp is described as:</p><blockquote>an instance of lodash with its methods wrapped to produce immutable auto-curried iteratee-first data-last methods</blockquote><p>Simple, right…? Let’s step through this bit by bit.</p><p><strong>Immutable </strong>— These functions do not mutate their arguments, but produce new instances every time they are called.</p><p><strong>Auto-curried </strong>— <a href="https://en.wikipedia.org/wiki/Currying">Currying</a> takes a function which receives multiple arguments and turns it into a series of <a href="https://en.wikipedia.org/wiki/Higher-order_function">higher-order functions</a>, each receiving a single argument. This is best explained by a simple example. Let’s say we have the function multiply:</p><pre>const multiply = (a, b) =&gt; a * b;</pre><pre>multiply(3, 5); // 15</pre><p>If we were to create a curried version of this it would look like this:</p><pre>const multiply = a =&gt; b =&gt; a * b;</pre><pre>multiply(3)(5); // 15</pre><p>Ok so it looks pretty much the same… actually it looks worse. But the benefit comes from the ability to create <a href="https://en.wikipedia.org/wiki/Partial_application">partially applied functions</a>, and from ending up with a complex function that only takes a single argument. We will discuss why this is good later.</p><p><strong>Iteratee-first data-last</strong> — If you look at a lodash function like map, it takes an array first, and then an iteratee (a function to be called on each element). It looks like this:</p><pre>const doubledNumbers = map(numbers, x =&gt; x * 2);</pre><p>Putting the iteratee first means we reverse the args and end up with this:</p><pre>const doubledNumbers = map(x =&gt; x * 2, numbers);</pre><p>But then because they are also curried, it’s actually like this:</p><pre>const doubledNumbers = map(x =&gt; x * 2)(numbers);</pre><p>So despite the wording, it’s all pretty simple, even if it doesn’t make sense why you would want those things yet.</p><p>So what’s the benefit?</p><ol><li>We can use these functions to create new useful, reusable functions. Let’s say we regularly want to filter negative numbers out of an array. Using regular lodash we would rewrite filter(arr, x =&gt; x &gt; 0) in each of those places. lodash/fp would allow us to create a partially applied function filterNegative = filter(x =&gt; x &gt; 0) and use that everywhere we need it. That’s pretty cool, although not really the biggest benefit since even if the iteratee part got more complicated you could always extract that out into a separate function.</li><li>The bigger benefit comes when you start to compose functions. compose is an alias of <a href="https://lodash.com/docs/4.17.4#flowRight">flowRight</a>, which creates a function that calls each of the provided functions in order from right to left, passing the output of one function as the input to the next:</li></ol><pre>const composedFunction = compose(f, g, h);</pre><pre>// roughly equivalent to</pre><pre>const composedFunction = x =&gt; f(g(h(x)));</pre><p>Since a function can only return a single value, compose wants a series of functions which each receive a single value so it can chain them together. Using the auto-curried iteratee-first data-last methods, we can easily create functions that work well with compose. Let’s say we wanted to filter negative numbers, then double all remaining numbers, then add 5 to each of them. Using lodash/fp we can achieve it like this:</p><pre>const filterNegative = filter(x =&gt; x &gt; 0);<br>const mapToDouble = map(x =&gt; x * 2);<br>const mapToPlus5 = map(x =&gt; x + 5);</pre><pre>const f = compose(mapToPlus5, mapToDouble, filterNegative);</pre><pre>f([-3, -2, -1, 0, 1, 2, 3]); // [5, 7, 9, 11]</pre><p>By following this functional approach, we can easily compose new complex functions using simple building blocks.</p><h3>Composition in React</h3><p>The way React components are designed makes it very easy to compose them. A React component can control how another component is rendered by providing props to it, and even control whether it is rendered at all. As an example, let’s make a button which logs all clicks to the console:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4cbe9bcb835a2b8714ac4852bedcf74/href">https://medium.com/media/d4cbe9bcb835a2b8714ac4852bedcf74/href</a></iframe><p>This component passes all props given to it down to the button, but mutates the onClick callback to add a log message. As a result, this component can be used as a drop in replacement for any &lt;button&gt; components in your app. Unfortunately, if we wanted to reuse this logic for other components, we would have to rewrite the entire thing. The good news it that we can make it a <a href="https://facebook.github.io/react/docs/higher-order-components.html">higher-order component</a> and provide the component to wrap, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99dad85fc5daf4146cbedda2da57f2ad/href">https://medium.com/media/99dad85fc5daf4146cbedda2da57f2ad/href</a></iframe><p>We can then recreate the ClickLoggingButton from before by providing the component (or in the case of built in components, the string identifying the component) to the higher-order component:</p><pre>const ClickLoggingButton = clickLoggingHoc(&#39;button&#39;);</pre><p>Now it’s starting to look like something we could compose. We could even make this more generic and log a custom message any time any callback is called by wrapping the higher-order component in a function, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a4efe7d916f8720ffb74a4ba6bb6807/href">https://medium.com/media/5a4efe7d916f8720ffb74a4ba6bb6807/href</a></iframe><p>And then recreate our old higher-order component and button component:</p><pre>const clickLoggingHoc = callbackLoggingBuilder(&#39;onClick&#39;, &#39;click&#39;);<br>const ClickLoggingButton = clickLoggingHoc(&#39;button&#39;);</pre><p>Now let’s say we wanted to log all calls to onClick and onChange. In our original implementation we would have to rewrite a lot of logic into two higher-order components, but now we can simply write this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa1f6f9f038b82887e01ce93ae4756b1/href">https://medium.com/media/aa1f6f9f038b82887e01ce93ae4756b1/href</a></iframe><p>One important point is that we created a function which returned the higher-order component, rather than just passing in additional props with the wrapped component. We could have written it like this:</p><pre>const callbackLoggingBuilder = (propName, msg, WrappedComponent) =&gt; ...</pre><pre>const clickLoggingButton = clickLoggingHoc(&#39;onClick&#39;, &#39;click&#39;, &#39;button&#39;);</pre><p>But then we wouldn’t be able to use compose. By using <a href="https://en.wikipedia.org/wiki/Partial_application">partial-application</a>, we can pre-define the other arguments and create an easily composable function which takes a react component, and returns a new react component.</p><h3>A Real World Example</h3><p>A lot of the time we want to get some data from a server somewhere. To do that you make a request and most likely get back a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a> which will eventually be either resolved or rejected. During the loading time, you want to display some kind of loading indicator and if the request fails you want to show some kind of error. Here is a pretty typical implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/943936b15dee08d131ab2530d51c5460/href">https://medium.com/media/943936b15dee08d131ab2530d51c5460/href</a></iframe><p>That’s a lot of boilerplate for every time we want to track the state of a promise. What if we try to extract it to a higher-order component? We could make a component which receives a callback that returns a promise as a prop, and wraps that callback with promise tracking logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/024d469a6e87c2c774cf222d1e62ae61/href">https://medium.com/media/024d469a6e87c2c774cf222d1e62ae61/href</a></iframe><p>Now we can recreate our old component in two parts without all the promise stuff:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8cf379c21763c64a54bb059efbda059/href">https://medium.com/media/c8cf379c21763c64a54bb059efbda059/href</a></iframe><p>That’s a lot simpler. The first component simply provides a prop to make the request, then the promise tracking component wraps that callback, and then the last component uses those promise props to render everything correctly. These components are no longer responsible for tracking the state of the promise and we can write the makeRequest method without having to worry about generic promise logic. The render method still contains a lot of boilerplate though, let’s try to extract that too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/158a268bac0987e112d5d3737ce74472/href">https://medium.com/media/158a268bac0987e112d5d3737ce74472/href</a></iframe><p>And recreate the component again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604eb5b2fb03dda51c70454350a0acc1/href">https://medium.com/media/604eb5b2fb03dda51c70454350a0acc1/href</a></iframe><p>We have managed to remove all of the boilerplate from our Example component and recreate it by composing several simple higher-order components together. Now whenever we want to track a promise, render loading indicators, or render errors from any component we can always compose these together without having to duplicate the logic. Testing the Example component is also a lot simpler. As long as we ensure that the makeRequest method returns a promise we can trust that our generic higher-order components will take care of everything else.</p><p>One small issue here is that the loading, data, and error props are hard-coded, meaning we have to be careful about passing in other props with these names as they will be overwritten. We can always namespace these props with the name of the function being wrapped:</p><pre>const newProps = {<br>  [`${propName}Loading`]: loading,<br>  [`${propName}Data`]: data,<br>  [`${propName}Error`]: error<br>}</pre><p>Or we could simply provide the names of the new props as arguments to the function. Either way, by doing this you can avoid issues regarding pre-existing props being overwritten.</p><p>For a more complete example, check out this <a href="https://jsfiddle.net/vs9hu26n/">JSFiddle</a>. By default network requests are made to fail 50% of the time to test the error handling, so if you see the message ‘something went wrong try again’ click the link to retry.</p><p>If you think this technique is useful, check out <a href="https://medium.com/@mjewell/designing-react-components-for-modularity-reusability-and-testability-edf4a68147e9">my previous post</a> explaining some more benefits of constructing your app out of higher-order components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=527f6930a42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing React Components for Modularity, Reusability, and Testability]]></title>
            <link>https://medium.com/@mjewell/designing-react-components-for-modularity-reusability-and-testability-edf4a68147e9?source=rss-2cf8709f7781------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf4a68147e9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Michael Jewell]]></dc:creator>
            <pubDate>Mon, 13 Mar 2017 14:17:07 GMT</pubDate>
            <atom:updated>2017-03-13T15:57:49.611Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibility principle</a> states that each component of a system should only do one thing. It’s a pretty widely accepted best practice, but it can be hard to follow at times. By sticking to this principle you can build a system which minimizes the impact of changing requirements, simplifies testing, and reduces the overall complexity of your code base.</p><p>In most react examples a single component will handle two broad responsibilities — how it looks, and how it works. This definitely sounds like it’s breaking the single responsibility principle. Fortunately, it’s not too hard to get around this.</p><h3>Presentational and Container Components</h3><p>A well-known pattern to separate concerns is to use <a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.u1df8j9ea">Presentational and Container Components</a>. You should definitely read that article (and <a href="https://medium.com/@learnreact/container-components-c0e67432e005#.4tsd1jebj">the one it is based off</a>) if you haven’t already, but fundamentally they suggest having a container component that controls the logic, which renders a presentational component that controls the look and feel. This is a great way to design your components, but it does have some problems.</p><h4>Issues — Testing</h4><p>In a realistic application we will probably have a pretty large tree of components. It might look something like this:</p><pre>                                +-&gt; ContainerB -&gt; PresenterB -&gt; ...<br>                               /<br>App -&gt; ContainerA -&gt; PresenterA<br>                               \<br>                                +-&gt; ContainerC -&gt; PresenterC -&gt; ...</pre><p>We’re good developers, let’s say we wanted to write some tests. We will start with PresenterA. Using <a href="https://github.com/airbnb/enzyme">enzyme’s</a> shallow method we can isolate this component and effectively ignore the rest of the tree. We know that we can use shallow instead of mount because we make sure our presenters do not contain any logic beyond presentation. As a result, no matter how complicated the downstream dependencies of PresenterA are, we can effectively ignore them for tests. This is great.</p><p>Now we want to test ContainerA. Sometimes we will be able to use shallow, but we can’t guarantee it. There will definitely be times we have to do full DOM rendering with mount and when we do we are forced to render the entire tree below the component under test. This can significantly slow the tests down, but worse than that it can force you to deal with any dependencies of downstream components, like stubbing AJAX calls, even though they’re not really relevant to this particular test. This sucks.</p><h4>Issues — Reuse</h4><p>Sometimes our containers have pretty widely applicable logic in them. Let’s say we make a request and while we are waiting we want to render a loading indicator. There’s a pretty good chance that is going to be reused, but since our container is hard-coded to render it’s own presenter component, we have to rewrite this logic each time.</p><h3>What’s Really the Problem?</h3><p>At the core of both of the issues is the fact that the presenter is hard coded into the container. Let’s say we have this totally useless container:</p><pre>class Container extends React.Component {<br>  render() {<br>    return &lt;Presenter {...this.props} /&gt;;<br>  }<br>}</pre><p>What if we were to inject the presenter component and dynamically create the class instead, like this:</p><pre>function createContainer(WrappedComponent) {<br>  return class Container extends React.Component {<br>    render() {<br>      return &lt;WrappedComponent {...this.props} /&gt;;<br>    }<br>  }<br>}</pre><pre>const Container = createContainer(Presenter);</pre><p>Now we have a function which returns a container, but we can call it with any component we want. In this case, we also create our old container by calling this function with our presenter. A function like this is called a Higher-Order Component.</p><h4>Higher-Order Components as Containers</h4><p><a href="https://facebook.github.io/react/docs/higher-order-components.html">Higher-Order Components</a> (HOCs) are functions which take a react component and return a new component. They are able to control when the passed in component is rendered, and modify, add, or remove any props that are passed in. Containers basically just intelligently pass props down to their presenters, so these should be able to do everything we need.</p><h4>What Do We Gain?</h4><p>By doing this we are able to isolate the container component in the test environment and ignore all downstream dependencies. We can easily set up a test like this by passing in some dummy component:</p><pre>const Dummy = () =&gt; &lt;div /&gt;;<br>const ContainerUnderTest = myHigherOrderComponent(Dummy);</pre><p>Now even if we use mount we know that our test is only dealing with what happens inside the container we are currently testing. We can easily look at its internal state and the props provided to the Dummy component and know that our presenter will receive those props.</p><p>You may still want to test the container that renders your presenter, and you still can, exactly how you were before. Those tests have all the downsides listed previously, but hopefully you won’t need as many since you can cover most cases using the dummy component.</p><p>We are also able to reuse this container logic in any other parts of our app without having to rewrite it for specific cases. We can wrap any component with this higher-order component without making any modifications and it will receive whatever functionality it provides. By making it easy to reuse these components we encourage building our app out of small components with single responsibilities. Ultimately, this should help us create a well structured app.</p><h4>What Do We Lose?</h4><p>As far as I can tell, the only downside to this approach is the added boilerplate of wrapping your components in functions. There is some added complexity in understanding what is going on but the pattern is very consistent regardless of what your containers do, making it pretty easy to learn.</p><h4>Chaining Higher-Order Components</h4><p>Sometimes our containers get pretty big, and when they do, they probably handle more than one responsibility. It would be great if we could split any unrelated container logic into different components and use them all with a single presenter. Because these higher-order components just take any component, we can chain these functions together easily:</p><pre>const Container = HOC1(HOC2(HOC3(Presenter)));<br>// or<br>const composedHOC = lodash.flowRight(HOC1, HOC2, HOC3);<br>const Container = composedHOC(Presenter);</pre><p>Both of these approaches create a chain of components like this:</p><pre>-&gt; HOC1 -&gt; HOC2 -&gt; HOC3 -&gt; Presenter</pre><h4>Customizing Higher-Order Components</h4><p>Sometimes you want to be able to customize how your HOCs work without having to rewrite them. The fact that HOCs take only a single parameter is pretty nice for chaining them, so how can we add other parameters without losing this? Just like before, let’s just wrap it in a function. Wrapping the HOC in another function allows us to provide any additional data we want and still end up with a function which takes only a single parameter, a component to wrap:</p><pre>function myHigherOrderComponentBuilder(options) {<br>  return function myHigherOrderComponent(WrappedComponent) {<br>    return class extends React.Component {<br>      // we can use `options` in here to configure our container<br>    }<br>  }<br>}</pre><pre>const myBlueHigherOrderComponent = myHigherOrderComponentBuilder({<br>  color: &#39;blue&#39;<br>});</pre><pre>const Container = myBlueHigherOrderComponent(Presenter);</pre><h4>Example</h4><p><a href="https://jsfiddle.net/2k5qj53t/">This JSFiddle</a> covers the main uses of this technique and shows a simple presenter being enhanced by HOCs. The example is pretty basic but the patterns described can easily be extended to real-life use cases.</p><p>Hopefully it’s clear how using higher-order components can help you build easily testable and reusable container components. In my opinion the benefits heavily outweigh the cost of the small amount of boilerplate required to generate the higher-order components. Although HOCs can seem daunting at first, it’s important to understand that ultimately we created the same container component we would have created normally. This means you can easily try out this method on a single component and see the benefits yourself without having to refactor anything outside of it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf4a68147e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[formobx: Simple forms with MobX]]></title>
            <link>https://medium.com/@mjewell/formobx-simple-forms-with-mobx-fe373e1e52b0?source=rss-2cf8709f7781------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe373e1e52b0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobx]]></category>
            <dc:creator><![CDATA[Michael Jewell]]></dc:creator>
            <pubDate>Sun, 08 Jan 2017 21:41:42 GMT</pubDate>
            <atom:updated>2017-01-08T21:41:42.994Z</atom:updated>
            <content:encoded><![CDATA[<p>Chances are, a lot of web development you do revolves around writing forms. With <a href="https://github.com/mobxjs/mobx">MobX</a>, state management is generally a breeze, but I found myself to be writing a lot of boilerplate when it came to making forms, especially as they became more complex. Most of the time it wasn’t anything too complicated, just repetitive. Eventually though, in a realistic use case, you probably have more requirements than just storing the values, like attaching errors to fields. Once you get to more complex forms with nested objects or arrays of fields it can become less simple and more error prone to handle this data. Fortunately for the redux users there’s a great library called <a href="http://redux-form.com/">redux-form</a> which removes a lot of this common code. Unfortunately, I couldn’t find a suitable alternative for MobX.</p><h4>Introducing formobx</h4><p>f<a href="https://github.com/mjewell/formobx">ormobx</a> makes it easy to create forms by using the <a href="https://facebook.github.io/react/docs/context.html">React Context</a> to infer the structure of the backing form object based on the structure of your react components. This makes it extremely easy to build complex forms with easily reusable components. Let’s go through an example to demonstrate the main functionality.</p><h4>Step 1 — Create a Reusable Input Component:</h4><pre>import { field } from &#39;formobx&#39;;</pre><pre>const MyField = <strong>field(</strong><br>  ({ <strong>field</strong>, type, name }) =&gt; (<br>    &lt;div&gt;<br>      &lt;label&gt;{name}: &lt;/label&gt;<br>      &lt;input<br>        {<strong>...field.asProps</strong>}<br>        type={type}<br>      /&gt;<br>      {<strong>field.errors</strong>.map(error =&gt; &lt;p&gt;{error}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  )<br><strong>)</strong>;</pre><p>This component is mostly pretty standard React stuff. The key points are that it is wrapped with the formobx field function, and that it receives a special prop called field. This prop is actually an instance of a formobx FieldStore which represents the state of this input field. Importantly, this object has a getter called asProps which returns an object with value and onChange properties to make it easy to update this field object whenever the user changes the input. In more complex cases, you can overwrite these properties and update the field manually. The field object also has an errors property which contains an array of errors associated with this field. How these errors are assigned will be explained later.</p><h4>Step 2 — Create a Form Wrapper:</h4><pre>import { form } from &#39;formobx&#39;;</pre><pre>const MyFormWrapper = <strong>form(</strong>{<br>  onSubmit: form =&gt; console.dir(form)<br>}<strong>)</strong></pre><p>The form method accepts an options object and returns a new function which you can use to wrap your form component to give it formobx capabilities. The onSubmit function will receive the entire state of the form as its first argument and can optionally return a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> which will cause the submitting state of the form to be set to true until it is resolved or rejected. If the promise is rejected, formobx expects the reason for rejection to be an object shaped like the form containing arrays of errors for each field. Error messages from the reason for rejection will be added to the errors property of their respective field stores and can then be rendered by your input components.</p><h4>Step 3 — Create a Form Component:</h4><pre>const MyForm = <strong>MyFormWrapper(</strong><br>  ({ <strong>form</strong>, <strong>onSubmit</strong>, title }) =&gt; (<br>    &lt;form onSubmit={<strong>onSubmit</strong>}&gt;<br>      &lt;h1&gt;{title}&lt;/h1&gt;<br>      &lt;<strong>MyField</strong> name=&quot;email&quot; type=&quot;text&quot; /&gt;<br>      &lt;<strong>MyField</strong> name=&quot;password&quot; type=&quot;password&quot; /&gt;<br>      &lt;button type=&quot;submit&quot; disabled={<strong>form.submitting</strong>}&gt;<br>        Log In<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  )<br><strong>)</strong>;</pre><p>Again, this is all pretty standard react. We made a stateless functional component, wrapped it with the wrapper we created in step 2, and gave it the form and onSubmit props. We also used the custom input field component from step 1, but notice we did not have to pass in the field prop as formobx does this for us.</p><h4>Step 4 — Render the Form Component:</h4><pre>const App = () =&gt; (<br>  &lt;MyForm title=&quot;Hello Formobx&quot; /&gt;<br>);</pre><p>Finally, just render the generated form component from step 3, but there is no need to pass in the form or onSubmit props as those will also be provided for you.</p><p>This simple form will create a backing object that looks something like this:</p><pre>{<br>  email: &#39;&#39;,<br>  password: &#39;&#39;<br>}</pre><p>This structure was automatically determined by the name prop of the input fields in step 3. This object will be passed directly to the onSubmit function, but is also available through the form store via form.value. Similarly, to attach errors to this field you would return a rejected promise in the onSubmit function with an reason like this:</p><pre>{<br>  email: [&quot;can&#39;t be blank&quot;],<br>  password: [&quot;is not long enough&quot;]<br>}</pre><p>For more complex forms you may want arrays or objects, potentially nested inside one another. formobx makes this easy too. Simply add a parent component of either type ArrayField or ObjectField. For example, a more complex form component could look like this:</p><pre>import { ArrayField, ObjectField } from &#39;formobx&#39;;</pre><pre>const MyForm = MyFormWrapper(<br>  ({ form, onSubmit, title }) =&gt; (<br>    &lt;form onSubmit={onSubmit}&gt;<br>      &lt;h1&gt;{title}&lt;/h1&gt;</pre><pre>      &lt;ObjectField name=&quot;user&quot;&gt;<br>        &lt;MyField name=&quot;email&quot; type=&quot;text&quot; /&gt;<br>        &lt;MyField name=&quot;password&quot; type=&quot;password&quot; /&gt;<br>      &lt;/ObjectField&gt;</pre><pre>      &lt;ArrayField name=&quot;dogs&quot;&gt;<br>        &lt;ObjectField&gt;<br>          &lt;MyField name=&quot;name&quot; type=&quot;text&quot; /&gt;<br>          &lt;MyField name=&quot;color&quot; type=&quot;text&quot; /&gt;<br>        &lt;/ObjectField&gt;</pre><pre>        &lt;ObjectField&gt;<br>          &lt;MyField name=&quot;name&quot; type=&quot;text&quot; /&gt;<br>          &lt;MyField name=&quot;color&quot; type=&quot;text&quot; /&gt;<br>        &lt;/ObjectField&gt;<br>      &lt;/ArrayField&gt;<br>      <br>      &lt;button type=&quot;submit&quot; disabled={form.submitting}&gt;<br>        Log In<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  )<br>);</pre><p>which would create a backing object like this:</p><pre>{<br>  user: {<br>    email: &#39;&#39;,<br>    password: &#39;&#39;<br>  },<br>  dogs: [<br>    {<br>      name: &#39;&#39;,<br>      color: &#39;&#39;<br>    },<br>    {<br>      name: &#39;&#39;,<br>      color: &#39;&#39;<br>    }<br>  ]<br>}</pre><p>Notice that the elements of the array backing an ArrayField are based on how many formobx components are rendered inside of it so there is no need to keep track of this yourself — simply rendering components is enough. In fact, any backing object structure can be created by nesting these special components inside each other.</p><p>That should give a rough idea of how formobx can be used to create simple forms using MobX and React. For more comprehensive docs and examples take a look at it on <a href="https://github.com/mjewell/formobx">GitHub</a>.</p><h4>Coming Soon…</h4><p>Two common features for forms that are not currently handled by this library are client-side validations, and checking if fields have been modified by the user. Support for these features is currently in progress.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe373e1e52b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>