<?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 Joe Morgan on Medium]]></title>
        <description><![CDATA[Stories by Joe Morgan on Medium]]></description>
        <link>https://medium.com/@jsmapr1?source=rss-f920a515c4e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o-CwYjcK-0Fbn10p7RgGGA.png</url>
            <title>Stories by Joe Morgan on Medium</title>
            <link>https://medium.com/@jsmapr1?source=rss-f920a515c4e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 06:00:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jsmapr1/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[Optional Chaining]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/pragmatic-programmers/optional-chaining-990f7be828fc?source=rss-f920a515c4e0------2"><img src="https://cdn-images-1.medium.com/max/2600/0*tiqMByzvrr3-ispH" width="4032"></a></p><p class="medium-feed-snippet">Overcoming the Problem of Trust in JavaScript</p><p class="medium-feed-link"><a href="https://medium.com/pragmatic-programmers/optional-chaining-990f7be828fc?source=rss-f920a515c4e0------2">Continue reading on The Pragmatic Programmers »</a></p></div>]]></description>
            <link>https://medium.com/pragmatic-programmers/optional-chaining-990f7be828fc?source=rss-f920a515c4e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/990f7be828fc</guid>
            <category><![CDATA[chaining]]></category>
            <category><![CDATA[es6tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[articles]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Joe Morgan]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 10:32:16 GMT</pubDate>
            <atom:updated>2021-07-06T10:32:16.665Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Disguise Driven Testing: Jest Mocks In Depth Pt 1]]></title>
            <link>https://medium.com/@jsmapr1/disguise-driven-testing-jest-mocks-in-depth-pt-1-ffdb4631e76c?source=rss-f920a515c4e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffdb4631e76c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joe Morgan]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 17:18:31 GMT</pubDate>
            <atom:updated>2019-04-11T17:18:31.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9LWWd156Ww8CAqZm0GD5Q.jpeg" /></figure><blockquote>Originally published at <a href="https://ponyfoo.com/articles/disguise-driven-testing-jest-mocks-in-depth">Pony Foo</a>.</blockquote><p>Testing <em>can </em>be simple. In fact, it is simple. Well, it’s simple until impurities slip in.</p><p>Code that would be easy to test becomes a nightmare as soon as you get impure data (like date checks) or complex external dependencies (such as DOM manipulations or large 3rd party libraries). The part that tends to frustrate developers most is when they have code that’s easy to read, easy to write, but difficult to test. No one wants to spend more time on their tests than they do on their code.</p><p>Consider an example. Let’s say you needed to write some code that checks to see if a given date is two weeks from today. If they date is far enough away, you get an empty string. If the date is less than two weeks away, you get an error message:</p><pre>import moment from &#39;moment&#39;;</pre><pre>export const message = &#39;Date must be two weeks from now&#39;</pre><pre>export function isAtLeastTwoWeeks(date) {<br>  const isLater = moment(date).isAfter(moment().add(2, &#39;weeks&#39;));<br>  return isLater ? &#39;&#39; : message;<br>}</pre><p>That’s pretty simple code. But how do you write a test for it? Things can get tricky fast.</p><p>Here’s an even more basic example. You want to fetch some data from an api and display the first couple items:</p><pre>export function getRecent() {<br>  return fetch(&#39;/albums&#39;)<br>    .then(response =&gt; response.json())<br>    .then(albums =&gt; {<br>      return albums<br>        .reverse()<br>        .slice(0, 2)<br>        .map(({title}) =&gt; title);<br>    })<br>}</pre><p>Simple to read. Simple to understand. But how would you test it without hitting the live API?</p><p>There’s an unfortunate belief that testing is hard. Early in my career, I heard one developer estimate that it doubled development time. And he was arguing <em>for</em> testing, that it was worth the extra time. The problem is that most testing is easy. But testing impure functions can be very, very difficult.</p><p>Fortunately, the <a href="https://jestjs.io/">Jest testing framework</a> has simplified a lot of the complexities behind testing. The secret is a tool called a <a href="https://jestjs.io/docs/en/manual-mocks">mock</a>. A mock is effectively a shortened version of a function. Instead of running the function you stub out the result you want. Your code will return what you want instead of running the live code.</p><p>In other words, you say what an API <em>should </em>return. The mock will bypass the live api and return the data directly. Instead of relying on a date function that changes every 24 hours, you effectively freeze it in place by returning the same date every time.</p><p><strong>🚨 Warning 🚨</strong></p><p>Mocks are a great tool, but they should be a last resort. If your tests use a significant amount of mocks (or spies or stubs or other testing trick), consider refactoring first. After you have isolated the complexities as much as possible, then it’s time to use mocks.</p><h3>Jest: A Brief Intro</h3><p>Jest is a testing framework developed at facebook, it’s used most often with React, but it does work independently.</p><p>Jest offers runtime testing tools. an expect library and system for mocks and spies right out of the box.</p><p>At it’s most basic, a Jest test will look nearly identical to mocha or jasmine or any other framework. In fact, Jest started as a fork of Jasmine.</p><pre>import { double } from &#39;./double&#39;;</pre><pre>describe(&#39;Some Test&#39;, () =&gt; {<br>  it(&#39;should add two number&#39;, () =&gt; {<br>    expect(double(1)).toEqual(2);<br>  });<br>});</pre><p>In this case, toEqual is the assertion.</p><p>That’s pretty much all you need for the purposes of this article. There are plenty of extra features that you can read about in the <a href="https://jestjs.io/">documentation</a>. You can also look there for installation and configuration. If you want to follow along, check out the <a href="https://github.com/jsmapr1/jest-mock-dive">repo for this article</a>.</p><h3>Creating Testable API Functions</h3><p>Return to your API code. Now that you have your code and you have your test suite all set up, it’s time to write tests. As a reminder, you have a piece of code that fetches api data and parses the results.</p><pre>export function getRecent() {<br>  return fetch(&#39;/albums&#39;)<br>    .then(response =&gt; response.json())<br>    .then(albums =&gt; {<br>      return albums<br>        .reverse()<br>        .slice(0, 2)<br>        .map(({title}) =&gt; title);<br>    })<br>}</pre><p>The first step in creating a mock is isolating the pain point. In this case, the problem is the fetch block. Specifically this part:</p><pre>return fetch(&#39;/albums&#39;)<br>    .then(response =&gt; response.json())</pre><p>The rest of the code isn’t so bad. It’s just a series of array manipulations.</p><p>The next step if figuring out what kind of data from the hard part you expect to pass down to the easy part. Again, all you need to do is look at what the live API will return by either hitting it directly or by getting the contract from some other team. In this case, you plan to get the albums of the great doom metal band Sleep. The data you expect to get will look something like this:</p><pre>[<br>  {<br>    year: 1992,<br>    title: &#39;Holy Mountain&#39;<br>  },<br>  {<br>    year: 1999,<br>    title: &#39;Jerusalem&#39;<br>  },<br>  {<br>    year: 2014,<br>    title: &#39;The Clarity&#39;<br>  },<br>  {<br>    year: 2018,<br>    title: &#39;The Sciences&#39;<br>  },<br>];</pre><p>Now, you should split the function. Pull the hard part away from the easy part. That will make your tests cleaner and easier to mock.</p><p>As a quick side note, some consider it bad practice to break up your code to make it more testable. I would disagree. Testability tells you something about the complexity of your code. The harder it is to test, the more complex it tends to be. When you are refactoring your code to make it more testable, you just changing the complex to the simple.</p><p>Since you’ve isolate the complex part, the next the step is pulling the fetch call out into a separate function. Call the new functionservice and since it now has a separate responsibility go ahead and move it into a new file called service.js. To keep things clean, move it to a separate directory called api this will be important later when you set up the mock.</p><pre>export default function service() {<br>  return fetch(&#39;/albums&#39;)<br>    .then(response =&gt; response.json())<br>}</pre><p>Now you need to import the service and replace the original fetch method. Your original function will be a little smaller, but you still are able to perform the exact same actions as your did before:</p><pre>import service from &#39;../api/service&#39;;</pre><pre>export function getRecent() {<br>  return service()<br>    .then(albums =&gt; {<br>      return albums<br>        .reverse()<br>        .slice(0, 2)<br>        .map(({ title }) =&gt; title);<br>  })<br>}</pre><p>At this point, you should start to see an opportunity for a mock. Remember, a mock is just replacing a live piece of code with a simple function that returns the data you expect.</p><p>In this case, you have a function service that returns a Promise that returns some sort of array. You happen to know this service hits an API, but that doesn’t really matter. It can be loading data from localstorage as far as you’re concerned.</p><p>Time to jump into the test. Here’s what it’ll look like:</p><pre>import { getRecent } from &#39;./recent&#39;;</pre><pre>describe(&#39;getRecent&#39;, () =&gt; {<br>  it(&#39;should get albums&#39;, async () =&gt; {<br>    const albums = await getRecent();<br>    const expected = [<br>      &#39;The Sciences&#39;,<br>      &#39;The Clarity&#39;<br>    ]<br>    expect(albums).toEqual(expected);<br>  })<br>})</pre><p>Since getRecent returns a promise, you can use async/await syntax. This code says, run the getRecent function and once it resolves, make sure the albums are as expected.</p><p>Jest will wait for a promise to resolve if you return. That means you can also write the test like this:</p><pre>import { getRecent } from &#39;./recent&#39;;</pre><pre>describe(&#39;getRecent&#39;, () =&gt; {<br>  it(&#39;should get albums&#39;, () =&gt; {<br>    return getRecent()<br>      .then(albums =&gt; {<br>        const expected = [<br>          &#39;The Sciences&#39;,<br>          &#39;The Clarity&#39;<br>        ]<br>        expect(albums).toEqual(expected);<br>      })<br>  })<br>})</pre><p>Either way, you still need to account for the service. Currently, it will still try (and probably fail) to hit a live endpoint.</p><p>Now, it’s time to start mocking the results.</p><h3>Mocking an API Result</h3><p>There are multiple ways to mock data, but the easiest is by creating a manual mock at the same level as the code you need to bypass.</p><p>In practical terms, you are going to make a file of the same name that returns data that you want instead of executing a function to get that data.</p><p>Start by making a directory called __mocks__ in the <em>same</em> directory as service.js Suppose you had a directory called api that contained services.js, you’d add your __mocks__ in the same api directory like this:</p><pre>| api<br>  | __mocks__<br>    | service.js<br>  | service.js</pre><p>Inside __mocks__/service.js create a function with the same name, but that returns the data you want.</p><pre>const albums = [<br>  {<br>    year: 1992,<br>    title: &#39;Holy Mountain&#39;<br>  },<br>  {<br>    year: 1999,<br>    title: &#39;Jerusalem&#39;<br>  },<br>  {<br>    year: 2014,<br>    title: &#39;The Clarity&#39;<br>  },<br>  {<br>    year: 2018,<br>    title: &#39;The Sciences&#39;<br>  },<br>];</pre><pre>export default function service() {<br>  return Promise.resolve(albums)<br>}</pre><p>Just as with the actual service function. This one returns a Promise but unlike the original function, this one has the data hard coded. It will never change.</p><p>Now that you’ve set up your mock, you need to alert your test that you want to use the manual mock instead of the real function. To do that, you need to use jest.mock(path) where the path is the location of the file you want to mock.</p><p>Suppose you had a file structure like this:</p><pre>| albums<br>  | recent.js<br>  | recent.spec.js<br>| api<br>  | __mocks__<br>    | service.js<br>  | service.js</pre><p>In your test, add the line jest.mock(&#39;../api/service&#39;). Notice, you are not adding the path to the __mocks__ directory, you are using the same path as if you were importing the function. Jest will find the mock for you. You are using the same path as you would in recent.js.</p><pre>import { getRecent } from &#39;./recent&#39;;</pre><pre>jest.mock(&#39;../api/service&#39;);</pre><pre>describe(&#39;recent&#39;, () =&gt; {<br>  it(&#39;should get albums&#39;, async () =&gt; {<br>    const albums = await getRecent();<br>    const expected = [<br>      &#39;The Sciences&#39;,<br>      &#39;The Clarity&#39;<br>    ]<br>    expect(albums).toEqual(expected);<br>  })<br>})</pre><p>Now, you are not hitting a live api. You are hitting an internal simulation. And it only takes one line of code. You don’t need network connectivity. You don’t need to worry about results changing. You don’t need to spin up a separate service. Everything is happening internally.</p><h3>What’s next?</h3><p>Mocking api data is one of the best uses of mocks. Nearly all javasript projects need to be able to access remote data. However, mocks can do a lot more. They can also deal with complicated side effects such as date time or DOM manipulations. In the next part, you’ll see how to mock out moment.js and other libraries that return data that changes depending on the day or even the location of the test.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffdb4631e76c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React State: Choose Wisely]]></title>
            <link>https://medium.com/@jsmapr1/react-state-choose-wisely-1787ee1bf18a?source=rss-f920a515c4e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1787ee1bf18a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joe Morgan]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 17:13:30 GMT</pubDate>
            <atom:updated>2019-04-11T17:14:15.586Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s look at 3 ways of managing state in react.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYLB18NiZJNEwJhg0oXMWg.jpeg" /></figure><blockquote>Originally published at <a href="https://ponyfoo.com/articles/react-state-choose-wisely">Pony Foo</a>.</blockquote><p>There are plenty of options for managing state in a React app. But there’s very little guidance about which one you should use in any situation.</p><p>Let’s fix that.</p><p>The solution you pick to manage state should fit they way you want to <em>use</em> the items you hold in state. Your choice should also make it easy for you to update, reuse, and refactor your code. In other words, your choice of state management can make your life easy or hard.</p><p>Here’s a non-exhaustive list of things you should consider:</p><ol><li>How quickly can you add new state code?</li><li>How well encapsulated is your stateful data?</li><li>How easy is it to pull the data into a new component?</li></ol><p>Let’s use this list as a basis for comparing different ways of handling state. To do this, we’ll make the same simple component using three different forms of state handling. By making the same thing three ways, you’ll get a few nice perspectives.</p><p>First, you’ll see that any approach can solve any problem. This is important because if you know that you can solve nearly any problem with any form of state management, you can turn your attention from the technical problem of getting it working, to the more abstract problem of making it work well in your over all application.</p><p>Second, by making the same thing three ways, you’ll start to see the subtle differences which can become big headaches as an applications grows.</p><p>What are the three ways to manage state?</p><ol><li><strong>Local State</strong>: State stored directly on the component.</li><li><strong>Global State</strong>: A global store. In this example, you’ll use redux.</li><li><strong>Context</strong>: A newer API that lets you access state higher up the tree.</li></ol><p>Using the three points of comparison and the three ways of managing state, you’ll be able to build a nice table that will let you compare the different options.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ef8ed3202b64d5bbc2a82fe903f022d/href">https://medium.com/media/1ef8ed3202b64d5bbc2a82fe903f022d/href</a></iframe><p>Alright. Let’s get started.</p><p>You’ll be making a very simple counter. It’s just two things: the current count and a button to add to the current count. As mentioned you’ll have one for each type of state, but they all act exactly the same way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*06lW_nBFWL5Q_leRs6Ia2A.gif" /></figure><p>So far, nothing too exciting. The first thing you are going to do is make the presentation layer. This will be a simple reusable component that displays the count and the button. Making this independent is not only a good practice, it will also a show you how easy it is to swap different forms of state handling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8ce45e8ad96022b361c591e34882977/href">https://medium.com/media/b8ce45e8ad96022b361c591e34882977/href</a></iframe><p>Now that you have your basic display component, you can start to build the stateful components.</p><h3>Local State</h3><p>The first component you’ll build will store state locally, directly on the component.</p><p>All you need is a basic class with state as a property and a method to add to state. Pass both the count from the state object and the addOne() method into your presentation component and you’re all done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/591443f64a97b58cba2752d4b5d823ab/href">https://medium.com/media/591443f64a97b58cba2752d4b5d823ab/href</a></iframe><p>At this point, one thing should jump out: it’s easy. Even without knowing much about other forms of state handling, you can see this one is very simple to set up. But it gets even better.</p><p>With the introduction of <a href="https://reactjs.org/docs/hooks-overview.html">React Hooks</a>, you’ll remove nearly all the boilerplate code.</p><p>Here’s an updated version using react hooks that’s nearly identical to the official docs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/717606f8203ccab7bc1a803351f2d9e5/href">https://medium.com/media/717606f8203ccab7bc1a803351f2d9e5/href</a></iframe><p>As above, count is the stateful data, and add() is a method for updating state. It would really be difficult to make this easier.</p><h3>Global State</h3><p>The next component you’ll build will use a global store. In this example, you’ll use redux since it’s by far the most popular, but many of the issues would be the same if you were using other options like MobX or even Apollo and GraphQL.</p><p>We’ll move quickly past some of the complexities of implementing redux. If you need a refresher, check out the <a href="https://redux.js.org/">official docs</a>.</p><p>To start make an action to add an item to the global store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bdceff0b166cd257e59d3668a970c62/href">https://medium.com/media/2bdceff0b166cd257e59d3668a970c62/href</a></iframe><p>Next, make a reducer to actually store the count.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2acfc5c6e110e5edee836307c159b8a/href">https://medium.com/media/d2acfc5c6e110e5edee836307c159b8a/href</a></iframe><p>If you’ve worked with redux before you may have ignored this part, but it’s important to take a moment to think about what you just did here.</p><p>You just created a global state object with the a property of count . That property name is now unique for this particular action. If you wanted to create another property with a similar name you’d need to either give it a unique name such as clickCount or encapsulate one, the other, or both inside a nested object.</p><p>You’ll return to this idea in a bit. For now, use connect to pull the state into your display component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53b14ec7ba983c6c791b928e8e0a399d/href">https://medium.com/media/53b14ec7ba983c6c791b928e8e0a399d/href</a></iframe><p>Again, we won’t explore the details, but as a summary, the component is tapping into the global store so that you can both read from it, using mapStateToProps, and update it using mapDispatchToProps. Other than that, your display component doesn’t care where the data comes from.</p><p>So far, the thing that should jump out immediately is how much work is involved. There are more files, more imports, more complexity. That’s not a problem if the advantages outweigh the extra work — and they often will — but it is still something to consider.</p><h3>Context</h3><p>The final component will use context. This is a fairly new form of state handling that was introduced in React 16.3. Context is similar to local state in many ways, but it has a slightly different implementation.</p><p>To start off, you need to create a context. This will set up a couple defaults that you will use when you create an implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c185d10e5e760d303cc8cfb93e0cdd9/href">https://medium.com/media/7c185d10e5e760d303cc8cfb93e0cdd9/href</a></iframe><p>This sets the initial state of 0 and adds a noop function that you will override later.</p><p>To actually use context, you will first need to make a <strong>Provider</strong>. A provider is the base component that will hold the state object and the methods for updating the state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7d9cdb9fa5f4dc46d4aee14bd32d7a6/href">https://medium.com/media/f7d9cdb9fa5f4dc46d4aee14bd32d7a6/href</a></iframe><p>If you scroll up, you’ll notice this looks very similar to the local state component. The big difference is that you are combing the state and the update function in single object which you then pass down into a <strong>Provider</strong> component that wraps everything else. In this case, you are wrapping this.props.children but you can also wrap a component directly.</p><p>To use this component, you’d wrap some other components. In this case, you’ll wrap a single component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d33daae9976e5c47b46148de005a7989/href">https://medium.com/media/d33daae9976e5c47b46148de005a7989/href</a></iframe><p>Notice, you are not passing any props to OtherComponent . More clearly, you are not<em> explicitly </em>passing anything to OtherComponent. The provider is holding the state information so that you can tap into it later.</p><p>Even if you go several components deep, you will still be able to access the provider’s state. So if OtherComponent returns another component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/708586f80225632ea0f34b8f6260e613/href">https://medium.com/media/708586f80225632ea0f34b8f6260e613/href</a></iframe><p>And AnotherComponent returns yet <em>another</em> component. That information is still hanging in the background.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/782f273b06703a90c07db3314119e49b/href">https://medium.com/media/782f273b06703a90c07db3314119e49b/href</a></iframe><p>Ok, that’s far enough. It’s time to pull out the state and do something with it.</p><p>To get the information you need to create a <strong>Consumer</strong>. The consumer uses render props to pull out that single value object. Remember, value contains count and addOne . You can use destructuring as a short hand.</p><p>Now that you have the state and the function to update state, you can pass it into your display component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/642407548e7934f44262ddaca331004e/href">https://medium.com/media/642407548e7934f44262ddaca331004e/href</a></iframe><h3>Comparisons</h3><p>As you saw, any form of state handling can do the same thing. In reality, if you put effort into it, you can make any state handling system work for any piece of data in your application.</p><p>Of course, who wants to put effort into it? The goal is always less effort, better results. With that in mind, it’s time to compare the different approaches.</p><h3>Simplicity</h3><p>This is the easiest comparison. Nothing beats local state particularly when you use react hooks. It’s quick, it does that job and it’s easy to refactor into a more complicated system if necessary. As a rule, you should always start with local state. If you need something more complicated, you can refactor as you go.</p><p>For this reason, Local State wins for simplicity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42a034e59d45cd473d34a96876f44dff/href">https://medium.com/media/42a034e59d45cd473d34a96876f44dff/href</a></iframe><h3>Encapsulation</h3><p>Next, let’s explore how well the data is encapsulated. If data is well encapsulated, you can reuse a component multiple times without any concern that another component may accidentally change your state. Encapsulation isn’t necessarily a goal in itself. There are times where you absolutely want different components to access and modify shared data (more on that in the next section).</p><p>As with most things, it’s about predictability. If you expect a component to be independent, the data shouldn’t be open to modifications by other components.</p><p>To explore encapsulation, you’ll need to add multiple versions of a component to see how they interact.</p><p>To start off return to the original page that has all three components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*06lW_nBFWL5Q_leRs6Ia2A.gif" /></figure><p>The code looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b97e99fa21eabf0176d20e2eb3ab032/href">https://medium.com/media/6b97e99fa21eabf0176d20e2eb3ab032/href</a></iframe><p>You have a simple parent component that wraps one instance of each component. To test encapsulation, all you need to do is add a second instance.</p><p>Start off with the StateCounter component. The updated code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc78dcd96db0946eeecb2b267b287299/href">https://medium.com/media/bc78dcd96db0946eeecb2b267b287299/href</a></iframe><p>When you open that in the browser, you can easily see that the data is well encapsulated. Every time you click the add button, it only updates that count on that particular component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*RGAf3J5f2b0szskR_CYL6w.gif" /></figure><p>Now try adding a second redux component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14a4b4e79a00acfedfb7355334a78e18/href">https://medium.com/media/14a4b4e79a00acfedfb7355334a78e18/href</a></iframe><p>Open this in the browser and notice how different it is. Every time you click on <strong>Add </strong>, you update the data on both components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*QkuuA5-3fMmSiWPPQyD2eA.gif" /></figure><p>In this case, these components are not independent. You can alter the data in any component that use the same action.</p><p>Now, there are certainly ways around this. You can have an id on the global store for each component. You can use an array. You can use a different namespace. But the fact is that global stores are best for global data. Encapsulation is not a primary goal.</p><p>How about context? Well, this is were things get a little more tricky. What does it mean to add a second component? Does that mean you add a second consumer? In this case, that would mean adding a second OtherComponent under the same provider. Or do you add a second CounterProvider?</p><p>Why not both? First, add another provider. Then in the existing provider, add a second instance of OtherComponent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54c524327a0958e59f90e909cc1bbfd2/href">https://medium.com/media/54c524327a0958e59f90e909cc1bbfd2/href</a></iframe><p>Let’s see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zlTdUSFaVhgVhVPrCvCkDQ.gif" /></figure><p>When you click on the first component, the counter iterates, but the other counters do not. But when you click on the second context counter, it <em>will </em>change the third counter. Similarily, if you click on the third counter, it will change the second.</p><p>This means that context is somewhere in the middle. It can be encapsulated when you want it to be, and it can be global when you want it to be.</p><p>Now, this claim comes with a big caveat. The ability to share date or keep it private all depends on how you order the components. Anything in the same hierarchy as the provider will share data, anything outside will not. This means that you may have to move providers up or down depending on how you want to use the consumers.</p><p>Still, at this point, you can finish filling out the chart. Local state is well encapsulated and context can be. They each get a check. Global state is not well encapsulated to it does not get credit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c103d3ea984948366c7077b1d9f253ea/href">https://medium.com/media/c103d3ea984948366c7077b1d9f253ea/href</a></iframe><h3>Availability</h3><p>That just leaves one more area of concern: availability. The beauty part is that you don’t need to write any more code. Sometimes you want your data to be easy to access.</p><p>Consider a shopping cart. Pushing users to a sale is the most important thing your code can do. Consequently, nearly every part of your app will potentially need to know about the cart (how much is in it, the total, etc). This is data you want to make easily accessible.</p><p>In this case, you can use what you learned above. Local state, for example, could work, but you would have to store it so far up the component hierarchy that you’d be passing it down a lot of props.</p><p>Global state, on the other hand, was designed specifically for this. It’s an easy 👍.</p><p>Context as you saw above can either be global (at least depending on where you put it in the hierarchy) or encapsulated. Go ahead and give it credit.</p><p>The final comparison looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c79d9ddfc306e73da101ab7d5dfb4d4b/href">https://medium.com/media/c79d9ddfc306e73da101ab7d5dfb4d4b/href</a></iframe><p>You may look at this table and think that local state or context are somehow better. That’s not true. The best solution is the one that works best for your data and your app.</p><p>One thing that’s not reflected in this chart is the large collection of third-party code that ties in with a global store. If you want to use observables with your store, then you’re better off using <a href="https://github.com/redux-observable/redux-observable">redux-observables</a> than trying to roll your own solution.</p><p>Each of these solutions exist for a reason. Your job is to find the fit that makes your code easiest to build and maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1787ee1bf18a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t settle: how you can match your JavaScript collection to your goals]]></title>
            <link>https://medium.com/free-code-camp/dont-settle-how-you-can-match-your-javascript-collection-to-your-goals-c94cb994be4e?source=rss-f920a515c4e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94cb994be4e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Joe Morgan]]></dc:creator>
            <pubDate>Mon, 13 Aug 2018 19:02:14 GMT</pubDate>
            <atom:updated>2018-08-13T19:02:14.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kLrLgDZjAt0P_xNrM1qtg.jpeg" /></figure><p>I loved JavaScript even when the world hated it. But I always had a hard time justifying collections. Objects are kind of a key-value store, but not really. And they were horrible if you needed to sort or loop. Arrays were easier to loop over, but clunky if you needed to pull out a specific value without an index.</p><p>The sad truth is that most of the time developers would just grab whatever collection popped into their head first. Then torture it with conversions to get whatever they needed.</p><p>It was painful.</p><p>Things are different now. There are more collection types. There are more methods. There are better techniques and even one-line expressions to switch between collection types. Why then does it seem like we are still just guessing when we pick a collection type?</p><p>I speak regularly about <a href="https://www.youtube.com/watch?v=cT7TMzZ3Cnw&amp;list=PL_G_ImM6b7_e9WnnY1Hmy-culcW40LX1b&amp;index=21">JavaScript and code quality</a>. I’ve <a href="https://pragprog.com/book/es6tips/simplifying-javascript">written books</a> about new syntax. But I find that most developers, even experienced ones, don’t put much thought into their collection choice.</p><p>Time to end that. Not only do we have Arrays and Objects. We also have Maps, Sets, WeakMaps, and WeakSets.</p><p>So which should you choose? Each collection has ups and downs. But in general, there are three big factors that should influence your choice:</p><ul><li><strong>Iterable</strong>: Can you loop over the collection directly and access each member one at a time?</li><li><strong>Keyed</strong>: Can you find a value using a special key without worrying about the other collection members?</li><li><strong>Destructurable</strong>: Can you pull pieces of the collection into variables quickly and easily?</li></ul><p>Each collection type is strong in some areas and weak in others. There are other advantages and disadvantages, but these are the big three for most code.</p><h3>Arrays</h3><p>Arrays are probably the most flexible collection. That makes them a great point to start exploring collections.</p><p>Here’s a list of my grade school teachers (names changed to protect the innocent).</p><pre>const myTeachers = [&#39;Cooper&#39;, &#39;Simes&#39;, &#39;Butler&#39;];</pre><p>Arrays preserve order which is great since this is the correct order of my first, second, and third grade teachers. Since the order is meaningful and I happen to know the meaning, I can use <strong>destructuring</strong> to pull out the items into variables.</p><pre>const [firstGrade, secondGrade, ...others] = myTeachers.</pre><p>Destructuring is a quick way to pull information out of a collection into separate variables. It can also create subsets of information. The variablefirstGrade has the value ofCooper . The next variable, secondGrade is Simes . The last variable is a little different, using the three dots ... we are saving the rest of the variables, one in this case, as a separate array. That means others is also an array: [&#39;Butler&#39;] . In this case, the ... is a rest pattern. We’re saving the rest of the of values after all.</p><p>Back to my collection of teachers. Let’s say you don’t care about the order they taught me, you are more interested in an alphabetized list. Now, before you sort the array, remember, sorting is a mutating function, so the action will change the original array. And since the order matters, you don’t want to make a permanent change. Fortunately, it’s not a big problem since you can create a new array with the spread operator: [...myTeachers] .</p><p>The reason you can use the spread operator is that arrays have a built-in iterator<strong> </strong>which allows you to act on a collection one at a time. In other words, arrays are <strong>iterable</strong>. The spread operator takes those items and creates a new list one at a time. Putting the whole thing in square brackets creates a new array. The iterable property is also what lets you do nice things like loop using for...of or run a function on each item of the array as you would do with the .map and .reduce methods.</p><p>Back to sorting. Now that you can make a new array, you don’t have to worry about the mutations. The sort function is a one-liner.</p><pre>const sortedTeachers = [...myTeachers].sort();</pre><p>Since arrays are destructurable and iterable, you can pull out information easily or access each item one at a time. Seems pretty great, right? Of course, arrays are not perfect. Suppose you didn’t know the order of the array, but you did want my second-grade teacher. Now you have a problem. Since arrays are not keyed, you can’t just pull out the information you need. The best you could do is create a complicated array of pairs — an array containing two items — along with an array method to find the one you want.</p><pre>export const myTeacherPairs = [[&#39;first&#39;, &#39;Cooper&#39;], [&#39;second&#39;, &#39;Simes&#39;], [&#39;third&#39;, &#39;Butler&#39;]];</pre><pre>return teachers.find(teacherPair =&gt; teacherPair[0] === &#39;second&#39;);</pre><p>This is a little clunky. An array of pairs is super important and you’ll see more of them later, but this is a pretty inefficient way to handle data lookups.</p><p>The problems are that the collection is not <strong>keyed</strong>. Arrays are good at lots of things, but key-value stores are not one. So you’re in a bind. You like the destructuring properties and the iterables. But retrieving key-value information is not simple. This is usually when developers turn to objects. But before that here’s a summary of arrays:</p><p>✅ Destructurable</p><p>✅ Iterable</p><p>❌ Keyed</p><h3>Objects</h3><p>Most JavaScript developers instinctively reach for an object as soon as they need to store key-value pairs. Objects in JavaScript can get pretty complex. For the sake of this example, think of them as a simple way to pass data around. No functions. No this keyword. Just key-value pairs.</p><p>Start off by rewriting my array of teachers into an object:</p><pre>const teachers = {<br>  first: &quot;Cooper&quot;,<br>  second: &quot;Simes&quot;,<br>  third: &quot;Butler&quot;,<br>};</pre><p>If you needed to find just my second-grade teacher and didn’t care about the other parts of the object, you can pull it out directly: teachers.second . Even better, you can pull the value directly into a variable with destructuring. It’s a simple assignment as long as the variable matches the object key.</p><pre>const { second } = teachers;</pre><p>Destructuring is probably the biggest reason to use objects when passing around data. You can easily collect multiple values in an object and then pass it to another function where you can pull the information out again.</p><pre>function getSecondGradeInfo({ second }) {<br>  const school = &quot;Lakin&quot;;<br>  return {<br>    school,<br>    teacher: second<br>  }<br>}</pre><p>Things start to fall apart when you want to iterate over the object. You either have to convert some part of the object to an array or you have to use a for...in loop.</p><pre>Object.keys(teachers)<br>.map(grade =&gt; `${grade}:${teachers[grade]}`)<br>.join(&#39; &#39;);</pre><pre>let myTeacher = &#39;&#39;;<br>for(const grade in teachers) {<br>  myTeacher += ` ${grade}:${teachers[grade]}`;<br>}</pre><p>Things are getting a little messy already. You either have to iterate over keys or you have to mutate a variable. Worse still, objects don’t guarantee order. You can never trust your for...in loop to give the results in the sequence you want.</p><p>All of these problems come from an object’s lack of an iterable property. Object.keys and for...in both use the iterator that comes from converting keys to an array.</p><p>Beyond that, there are other problems with objects. There are limited key options. You can’t use <a href="http://speakingjs.com/es5/ch17.html#object_literals">numbers</a> as keys, for example. They aren’t as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Keyed_collections_Maps_Sets_WeakMaps_WeakSets">performant</a> as other collections. But for the most part, they are good for passing data around without a lot of loops.</p><p>To summarize:</p><p>✅ Destructurable</p><p>❌ Iterable</p><p>✅ Keyed</p><h3>Maps</h3><p>Maps are a new collection type for JavaScript. They are a proper key-value store. Which is just a way of saying they were designed specifically for that purpose. Unlike objects, you still have to explicitly create a new instance:</p><pre>const teachers = new Map();</pre><p>After that, you set each item by passing a key then a value as arguments.</p><pre>teachers.set(&#39;first&#39;, &#39;Cooper&#39;)<br>.set(&#39;second&#39;, &#39;Simes&#39;)<br>.set(&#39;third&#39;, &#39;Butler);</pre><p>To retrieve a value, you call the get() method along with the key name.</p><pre>teachers.get(&#39;second&#39;); // Simes</pre><p>This might look a little familiar already. It’s not much different thanlocalStorage.setItem(key, value which you may have used to store data between visits to a webApp.</p><p>As key-value stores, maps are pretty great. They take a wider <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared">variety of keys</a>. And while an objects lookup time is linear, a Map’s lookup time will be <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Keyed_collections_Maps_Sets_WeakMaps_WeakSets">logarithmic</a>.</p><p>But the biggest advantage is that they have a built-in iterable. That means you can do things like access key-value pairs directly:</p><pre>let myTeachers = &#39;&#39;;<br>for([grade, name] of teachers) {<br>  myTeachers += ` ${grade}:${name}`;<br>}</pre><p>A few things to say about that. It may look like you are destructuring the map at the start of the for loop. You actually aren’t. When you iterate over a map, you get back a pair with the key and the value. So you’re actually destructuring an array.</p><p>Next, you may notice that you’re still mutating a variable. That’s not so great. Fortunately, since a map is an iterable, you can use the spread operator to convert the map to an array of pairs. That means</p><pre>[...teachers]</pre><p>will become</p><pre>[<br>  [&#39;first&#39;, &#39;Cooper&#39;],<br>  [&#39;second&#39;, &#39;Simes&#39;],<br>  [&#39;third&#39;, &#39;Butler&#39;],<br>]</pre><p>With the map converted to an array, you can now map the items to create your string.</p><pre>[...teachers]<br>.map(([grade, name]) =&gt; `${grade}:${name}`)<br>.join();</pre><p>That means that you have access to all the array methods in three short characters.</p><p>Oh, and since it’s iterable, the order is preserved. If you add your first-grade teacher at the beginning, you’ll get it at the beginning.</p><p>So what are the disadvantages? The biggest is the lack of direct destructuring. You can’t pull a value out without either calling the get()method or by converting to an array. That means passing data between functions gets a little wordier. You also can’t represent maps as a JSON string. So you won’t pull maps from an API anytime soon.</p><p>Still, if you have data that you know you’ll want to loop over while still retaining the ability to pull data quickly with a key, maps are your best best.</p><p>To summarize:</p><p>❌ Destructurable</p><p>✅ Iterable</p><p>✅ Keyed</p><h3>Moving Between</h3><p>You probably noticed one frustrating pattern. There’s no one collection that can do it all.</p><p>Fortunately, that’s not as big of a problem as you may think.</p><p>You’ve already seen that you can convert a map to an array with the spread operator. You can also go the other way and convert an array to the map, by passing it into the constructor.</p><p>You can also speed up the initial creation process by passing an array of pairs:</p><pre>const myTeachers = [<br>  [&#39;first&#39;, &#39;Cooper&#39;],<br>  [&#39;second&#39;, &#39;Simes&#39;],<br>  [&#39;third&#39;, &#39;Butler&#39;],<br>]<br>const teachers = new Map(myTeachers);</pre><p>At this point, when you have a map, you essentially have access to both the properties of an array and the properties of a map with only a slight conversion.</p><p>Objects are getting better. With Object.entries() you can create an array of pairs from an object.</p><pre>const teachers = {<br>  first: &quot;Cooper&quot;,<br>  second: &quot;Simes&quot;,<br>  third: &quot;Butler&quot;,<br>};</pre><pre>const myTeachers = Object.entries(teachers);</pre><pre>myTeachers[0]<br>// [&#39;first&#39;, &#39;Cooper&#39;]</pre><p>That means when you have an object, you have access to array methods with a simple conversion. Going back, though, is a little harder. There’s currently a <a href="https://github.com/tc39/proposal-object-from-entries">proposal</a> for Object.fromEntries() that will take an array of pairs and create an object. But that’s still a little bit away.</p><p>However, once it’s here, you won’t be locked into any particular collection type. And that’s the best news of all. Once you can move easily and quickly between collections, you can start to leverage the best features of each. Destructuring values when it’s convenient, iterating when you need to.</p><p>In other words, you can look at the data you have and the code you need and pick the appropriate collection type. If another function needs a different type, write a simple conversion. No more guessing. No more frustrations. You can match your collection to your goals not your code to your collection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94cb994be4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/dont-settle-how-you-can-match-your-javascript-collection-to-your-goals-c94cb994be4e">Don’t settle: how you can match your JavaScript collection to your goals</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>