<?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 Steve Hankin on Medium]]></title>
        <description><![CDATA[Stories by Steve Hankin on Medium]]></description>
        <link>https://medium.com/@steven-hankin?source=rss-3f95198a309e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NMVmdXWWnBfqg3sqzpmTmg.png</url>
            <title>Stories by Steve Hankin on Medium</title>
            <link>https://medium.com/@steven-hankin?source=rss-3f95198a309e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:01:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@steven-hankin/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[Creating a Singleton in TypeScript]]></title>
            <link>https://medium.com/better-programming/creating-a-singleton-in-typescript-dc320904e058?source=rss-3f95198a309e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc320904e058</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Steve Hankin]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 20:16:08 GMT</pubDate>
            <atom:updated>2022-08-11T15:56:30.298Z</atom:updated>
            <content:encoded><![CDATA[<h4>A classless object approach to a well-known pattern — from JavaScript to TypeScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbD9qQduSd_byEYSP43VLA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Shubham Dhage</a> on <a href="https://unsplash.com/s/photos/one?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Often the design patterns are translated to JavaScript using the ES6 Class declaration, perhaps for a couple of reasons:</p><ol><li>Popular <a href="https://en.wikipedia.org/wiki/Singleton_pattern#:~:text=the%20singleton%20pattern%20is%20a%20software%20design%20pattern%20that%20restricts%20the%20instantiation%20of%20a%20class%20to%20one%20%22single%22%20instance.">definitions</a>¹ of design patterns use the <em>class</em> keyword</li><li>Java proliferates, and it is trivial to transfer existing patterns to JavaScript Classes (Design Patterns² emerged in 1994 and quickly became popular in Java a few years later)</li></ol><p>JavaScript is multi-paradigm and can also support class and non-class objects within the same codebase (a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#defining_classes">class</a> declaration is a syntactic sugar in JavaScript).</p><p>However, there is a general consensus that a class-free approach is better for various reasons³. Additionally, if you are using React and have migrated to Hooks⁴ since v16.8, you’ve probably stopped using classes or at least adding new ones.</p><h3>What is a Singleton</h3><p>Simply put, a Singleton is an object that can have only one instance.</p><p>It’s useful when sharing a single version of data and/or functions across multiple modules is needed. Perhaps you want to have the Authorisation Credentials declared once or create an Axios instance with decorated methods. It’s also very popular when creating a Logging instance.</p><p>If you’re using React, you can also create a Singleton simply by using the <a href="https://reactjs.org/docs/hooks-reference.html#usecontext"><em>useContext hook</em></a>. However, it is still educational and interesting to know how to construct Singletons from first principles.</p><h3>A Naive Implementation</h3><p>So, how could we create one?</p><p>The interface is straightforward. We just need a getInstance() function that will return one object instance. Repeated calls to this function (including across modules) must return the same instance too.</p><pre>const singleton = () =&gt; ({ name: &quot;I am not yet a singleton 😿&quot; })</pre><pre><br>/** Should return _the_ instance of a singleton, not new ones 😕 */</pre><pre>const getInstance = () =&gt; singleton();</pre><p>But we still need to be able to get the singleton. And only one version of it. So this falls short of the implementation requirements:</p><ul><li>Only can have one instance (getInstance() will create a new instance each time)</li><li>Global accessor (only accessible within the script)</li><li>Lazy initialisation is good (created when getInstance() called)</li></ul><p>That’s fine, though. The above example was just a trial approach to get started.</p><h3>An Improved JavaScript Implementation</h3><h4>Object closure</h4><p>At this point, we could use a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closure</a> to store the instance of the singleton. All definitions of JavaScript closures seem to concentrate on the lexical scope of functions, but it also applies to objects! In our case, the singleton can be stored inside an outer function and made available to an inner object that is returned. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e2ad6567d35857b0f2ba5c837d305d9/href">https://medium.com/media/8e2ad6567d35857b0f2ba5c837d305d9/href</a></iframe><p>I’m highlighting the above approach as a solution if you want to create a private yet accessible value within a script, but there is still room for improvement for our purposes.</p><h4>Module scope</h4><p>Modules were introduced in ES6 as script files that run in strict mode only, preventing functions and variables from appearing in the global scope.</p><p>Interestingly, modules are singletons; no matter how often they are imported, they are executed only once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19ecf7b154169737b8b3564cf9eec952/href">https://medium.com/media/19ecf7b154169737b8b3564cf9eec952/href</a></iframe><p>As a simple example, this works. As soon as the module is imported, the Immediately Invoked Function Expression (IIFE) will run and create a single instance. If we access it via getInstance(), we’ll always get the same singleton object.</p><p>However, you might have noticed a problem:</p><ul><li>Only can have one instance (module IIFE has done this for us)</li><li>Global accessor (accessible via the exported getInstance() — only need to import to any module that requires access to the singleton)</li><li>Lazy initialisation is not good (it’s created as soon as the module is imported)</li></ul><p>We can take advantage of the module scope to “hide” our singleton instance and control access to it, and we can discard the IIFE, which is no longer necessary:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f2beb5003c0e093fa0b3867522269ed/href">https://medium.com/media/4f2beb5003c0e093fa0b3867522269ed/href</a></iframe><p>OK, that resolves our issue with the Lazy Initialisation, and we now have something useful.</p><ul><li>Only can have one instance</li><li>Global accessor</li><li>Lazy initialisation (created on the first reference)</li></ul><p>One potential issue here is that the singleton returned can be modified by the client, so we can resolve that in JavaScript by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">freezing</a> the singleton object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/838df5aacc6c87770da2b65bdbf47002/href">https://medium.com/media/838df5aacc6c87770da2b65bdbf47002/href</a></iframe><p>But what if we want to take this further?</p><p>We haven’t yet introduced typings for a TypeScript implementation, so let’s do that. Also, what if we’d like to optionally initialise the Singleton with a value?</p><h3>A TypSscript Implementation</h3><p>The first step is to create some type for the Singleton’s value and make it accessible externally (since dependent functions will probably want to pass it around and include it in their typings)</p><pre>/**<br> * Type of whatever we want to store in the singleton<br> * In this case, it is an object with a name attribute<br> */</pre><pre>export type SingletonValue = {name: string};</pre><p>The actual type I’ve used is arbitrary but would be specific to the singleton’s usage unless we want a singleton builder, but that’s for another discussion.</p><p>The singleton itself can be generic, and as such, it could be extracted to a separate library if so desired. For now, I’ll keep it within the same module for simplicity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c06427d77ec6cff0670e83a237b69b2b/href">https://medium.com/media/c06427d77ec6cff0670e83a237b69b2b/href</a></iframe><p>Keeping idiomatic with TypeScript, we define a &lt;T&gt; generic for its contained value.</p><p>I’ve removed the Object.freeze() from the implementation to illustrate how compile-time TypeScript will help defend the implementation. If you’re using it within your code base, that should be fine, but when implementing a third-party library, you’d probably want to freeze it just in case.</p><p>Now we can include a private “instance” for our singleton within the module (recall that modules always run in strict mode, so any values will not be accessible unless we explicitly export them)</p><pre>/**<br> * The only instance of our Singleton<br> */<br>let instance: ReturnType&lt;typeof makeSingleton&lt;SingletonValue&gt;&gt;;</pre><p>This uses a “Utility Type” called <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype">Return Type</a> and specifies the type of the Singleton Value that it will store (i.e., the return type of the makeSingleton function when using a value of SingletonValue)</p><p>The final step is to handle an optional initialisation and specify the type of Singleton we’re creating. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26cc2d5294c06d30281b1c429a217117/href">https://medium.com/media/26cc2d5294c06d30281b1c429a217117/href</a></iframe><p>However, there is now a small issue that the initial value could be passed each time we subsequently call getInstance(). It’s not all that problematic since it is just ignored, but it might result in a misunderstanding.</p><p>The best approach is to throw an exception if the Singleton is already created. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7373d4cc6d1416a426e070cde6246045/href">https://medium.com/media/7373d4cc6d1416a426e070cde6246045/href</a></iframe><p>So we now have reached a final version that meets our requirements. Here’s what it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddb48695ff0786f1080a324646e7c0ea/href">https://medium.com/media/ddb48695ff0786f1080a324646e7c0ea/href</a></iframe><h3>Usage of the Singleton</h3><p>From any module, we can simply obtain the getInstance function:</p><pre>import getInstance from &quot;./Singleton&quot;;</pre><pre>const singleton = getInstance();</pre><pre>singleton.setValue({ name: &quot;what is in a name&quot; });</pre><pre>const theNameObj = singleton.getValue();</pre><p>Obtaining multiple references to the singleton will result in the same underlying object. Here’s the code:</p><pre>const singletonRef1 = getInstance();<br>const singletonRef2 = getInstance();</pre><pre>console.log(singletonRef1 === singletonRef2);  <em>// true</em></pre><p>Additionally, extending the Singleton is impossible since TypeScript will balk. Here’s the code:</p><pre>singleton.myExtraFunc = () =&gt; { /** some logic */ }</pre><pre><em>Property &#39;myExtraFunc&#39; does not exist on type &#39;{ getValue: () =&gt; Singleton | undefined; setValue: (value: Singleton) =&gt; Singleton; }&#39;.ts(2339)</em></pre><h3>Wrap Up</h3><p>Hopefully, you can see this article is more than just about implementing a Singleton in TypeScript and covers many interesting topics (closures, modules, IIFEs, generics, etc.)</p><p>Did you find this interesting?</p><p>What do you think of the final implementation? What would you do to improve it?</p><p>Let me know your feedback in the comments below!</p><h3><em>Resources</em></h3><p>[1]: Wikipedia. <em>Singleton Pattern</em>. <a href="https://en.wikipedia.org/wiki/Singleton_pattern">https://en.wikipedia.org/wiki/Singleton_pattern</a></p><p>[2]: Wikipedia. <em>Design Patterns</em>. <a href="https://en.wikipedia.org/wiki/Design_Patterns">https://en.wikipedia.org/wiki/Design_Patterns</a></p><p>[3]: Douglas Crockford. <em>Classical Inheritance in JavaScript</em>. <a href="https://www.crockford.com/javascript/inheritance.html">https://www.crockford.com/javascript/inheritance.html</a></p><p>[4]: ReactJs. <em>Hooks FAQ</em>. <a href="https://reactjs.org/docs/hooks-faq.html">https://reactjs.org/docs/hooks-faq.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc320904e058" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/creating-a-singleton-in-typescript-dc320904e058">Creating a Singleton in TypeScript</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Medium for Code Reviews]]></title>
            <link>https://steven-hankin.medium.com/a-simple-medium-for-code-reviews-4ba2b6bb99ed?source=rss-3f95198a309e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ba2b6bb99ed</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[simplicity]]></category>
            <dc:creator><![CDATA[Steve Hankin]]></dc:creator>
            <pubDate>Wed, 27 Jul 2022 21:30:26 GMT</pubDate>
            <atom:updated>2022-07-27T21:33:46.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Five stars on a desk" src="https://cdn-images-1.medium.com/max/1024/1*Huf4Bw-azrfUhQKwobG0IQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/s/photos/rating?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Back in 2017, I’d had enough of databases and decided I wanted to get into Front-end development. That’s a bit of a step-change, so I looked around for courses that were practical and opted for Full Stack Web Developer with <a href="https://www.udacity.com/nanodegree">Udacity</a>.</p><p>It’s straightforward, but a fair amount of work. Basically watch the videos, read the articles and occasionally submit a project.</p><p>This was where it got really, really interesting.</p><p>When you submit a project, it gets sent for evaluation by people who already use the technology professionally. They comb the code and point out improvements. Forgot to add a <a href="https://medium.com/easyread/one-of-the-important-skills-that-every-engineer-should-have-write-a-good-readme-85006c8b617b">README</a> or LICENSE.md? It comes back for rework. Bloated functions? Back again. Not met the objectives? No chance. And the comments were always disarmingly cheery.</p><p>And I loved it. Absolutely loved it.</p><p>I mean, how could reviews be fun? But it was. This was not only the fastest learning stages of the course, it was the fastest learning I <em>ever</em> had. When you have pro’s giving you the tips and the encouragement, you’re engaged and absorbing information at velocity.</p><p>Up until that point, most of my code had somehow avoided peer reviews (I mean c’mon, who would want to review database code? Seriously?). I was now enlightened and have always been excited to be on either side of reviews since.</p><p>Roll forward to 2022 and I’m working with ReactJS Developers and pondering how to effectively perform reviews.</p><h3>A Simple Method</h3><ol><li>Checkout the developer’s branch</li><li>Add TODO (or REVIEW) <em>comments</em> as close as possible to the code that needs attention</li><li>Commit / push the changes with a consistent commit <em>message</em></li><li>Developer can follow the recommendations, deleting completed TODOs</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSeIdbsvRGanRJSa4bDjnw.png" /><figcaption>Example TODOs in a React TSX file</figcaption></figure><h3>Benefits</h3><ul><li>Review comments are co-located with the target code; easier to follow that comments floating in a browser-based Pull Request</li><li>If you’ve been good with your Git messages, it will be straightforward to search the logs for the reviews if needed in the future</li><li>No licensed software is required</li></ul><p>I’m really interested how everyone else likes to do their reviews. Do you already follow this approach? Perhaps you prefer to use software solutions? Or are “over-the-shoulder” reviews the only way to go?</p><p>Let me know your opinion in the comments section below! 👏🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ba2b6bb99ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Useful Patterns for React Query]]></title>
            <link>https://steven-hankin.medium.com/3-useful-patterns-for-react-query-f3b0c98d77df?source=rss-3f95198a309e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3b0c98d77df</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Steve Hankin]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 19:26:42 GMT</pubDate>
            <atom:updated>2021-02-18T09:53:54.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qvZCOMKh9xnJWaTi" /><figcaption>Photo by <a href="https://unsplash.com/@alexloup?utm_source=medium&amp;utm_medium=referral">Alex Loup</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re using ReactJS, there is a good chance that you access a data service that supports either REST or GraphQL</p><p>Interacting with a data layer presents numerous problems:</p><ul><li>Duplicate requests (e.g. multiple components calling one endpoint)</li><li>Caching data</li><li>Updating stale data</li><li>Handling transitions from loading to success/error</li></ul><p>I’ve been using <a href="https://react-query.tanstack.com/">React Query</a> to wrap an <a href="https://www.npmjs.com/package/axios">Axios</a> layer inside a Typescript React app and find it a real joy to work with, eliminating a lot of the usual boilerplate code that was both bloating the codebase and sometimes causing bugs due to inconsistencies in approach</p><p>The bulleted issues above are listed in the <a href="https://react-query.tanstack.com/overview">React Query documentation</a> and a comparison of React Query vs other libraries is available <a href="https://react-query.tanstack.com/comparison">here</a>. If you’re not already using a library, I’d highly recommend spending half an hour looking at React Query</p><p>But out of the box I was encountering a few problems that weren’t immediately obvious from the documentation. I’ll discuss my solutions here and if you have alternatives I would be very interested to hear!</p><h3>How React Query works</h3><p>If you already use React Query, then you can skip this.</p><p>The React Query API declares a dependency on an asynchronous data source using a React Hook:</p><pre>const myQuery = useQuery(<strong><em>key</em></strong>, <strong><em>asyncFetchFn</em></strong>)</pre><p>The hook typically accepts a tuple specifying a key (which can be a simple string or an <a href="https://react-query.tanstack.com/guides/query-keys#array-keys">array</a>) and an asynchronous function to fetch the data, but we’ll see another approach in the next section</p><h3>#1 — Sharing queries across components</h3><p>Let’s take a simple example where we’ll get the latest Bitcoin prices from the <a href="https://www.coindesk.com/coindesk-api">Coindesk API</a>:</p><pre>export const getPrices = async () =&gt; <br>   (await   <br>      fetch(&quot;https://api.coindesk.com/v1/bpi/currentprice.json&quot;)<br>   ).json();</pre><p>This gives current prices in multiple currencies. If we wanted to use this data in different components (e.g. one component uses the prices for a table or chart and another component perhaps uses the timestamps) then we’d need a way to share the React Query call so that the first call will perform the GET and the second would benefit from the cache.</p><p>One way would be to make identical calls such as the following:</p><pre><strong>Component1.tsx:</strong><br>const currentPrices = useQuery(&quot;currentPrices&quot;, getPrices)</pre><pre><strong>Component2.tsx:</strong><br>const currentPrices = useQuery(&quot;currentPrices&quot;, getPrices)</pre><p>As long as both queries pass the same Query Key and Query Function, we’ll be able to leverage the React Query cache.</p><p>But having hardcoded text for the key is fragile. How about extracting a constant? We could do that and that would help protect against typos, but it still doesn’t give us the tight association between the key and the query function.</p><p>It might also be tempting to consider pushing the “useQuery()” into a shared function, but this will throw an error that the <a href="https://reactjs.org/docs/hooks-rules.html">Rules of Hooks</a> are being violated (specifically that hooks should be declared at the top-level of components)</p><p>This is where we can use the <a href="https://react-query.tanstack.com/guides/query-functions#using-a-query-object-instead-of-parameters">Query Object</a> form.</p><p>First, let’s create a function that returns a Query Object:</p><pre>export const getPricesQO = () =&gt; <br>({<br>   queryKey: &quot;currentPrices&quot;,<br>   queryFn: getPrices<br>});</pre><p>Next, we can reference the QO in our components:</p><pre><strong>Component1.tsx</strong><br>const currentPrices = useQuery(getPricesQO())</pre><pre><strong>Component2.tsx</strong><br>const currentPrices = useQuery(getPricesQO())</pre><p>Perhaps we want to make the query cached depending on the currency? We could easily pass in a currency and make the query key an array as follows:</p><pre><strong>api.ts</strong><br>export const getPricesQO = (<strong>ccy</strong>) =&gt; <br>({<br>   queryKey: <strong>[</strong>&quot;currentPrices&quot;<strong>,</strong> <strong>ccy]</strong>,<br>   queryFn: getPrices(<strong>ccy</strong>)<br>});</pre><pre><strong>Component1.tsx</strong><br>const currentPrices = useQuery(getPricesQO(<strong>ccy</strong>))</pre><h3>#2 — Data transformation</h3><p>Often we’ll need to transform the data structurally or extract subsets depending on the context. For example, I mentioned executing and caching the same query for different parameters. In this case, the query already provides multiple currencies in the same response</p><p>So how do we retrieve the currencies separately?</p><p>The first reaction might be to consider modifying the query object to accept the currency as a parameter (as I mentioned previously), but this has a downside; the different key will result in a cache-miss and the API being called again</p><p>Instead, we can use the “select” option which accepts a function that returns a data view.</p><p>For example, suppose we want to separately extract the GBP and Time data from the resolved query. We could define two new query objects that define select functions:</p><pre>/**<br> * Selects only GBP from Query<br> */<br>export const getGbpQO = (params?: {<br>   enabled?: boolean;<br>}): QueryObserverOptions&lt;BpiData, unknown, <strong>GBP</strong>&gt; =&gt; ({<br>   ...pricesDefaults(params?.enabled),<br>   <strong>select: (_) =&gt; _.bpi.GBP</strong>,<br>});</pre><pre>/**<br> * Selects only Time from Query<br> */<br>export const getTimeQO = (params?: {<br>   enabled?: boolean;<br>}): QueryObserverOptions&lt;BpiData, unknown, <strong>Time</strong>&gt; =&gt; ({<br>   ...pricesDefaults(params?.enabled),<br>   <strong>select: (_) =&gt; _.time</strong>,<br>});</pre><h3>#3 — Conditionally suppressing queries</h3><p>Often when components are bootstrapped, their key data might be undefined. In these situations, you would probably want to prevent the query from running at all, especially if the query relies on the missing key. Typically you’ll encounter this when a subcomponent needs something from the parent that isn’t available yet (imagine: Amazon Orders, where each order is a component mapped from a parent query that hasn’t completed yet)</p><p>Since React Query is implemented as hooks, it’s going to run as soon as the Component is rendered, whether you like it or not, but you don’t need to suddenly start wrapping the component in conditionals</p><p>Instead, there is a flag available in the Query Object called “enabled”</p><pre>export const getPricesQO = (params?: {<br>   enabled: boolean;<br>}): QueryObserverOptions&lt;BpiData, Error&gt; =&gt; ({<br>   queryKey: &quot;currentPrices&quot;,<br>   queryFn: getPrices,<br>   <strong>enabled</strong>: params?.enabled === true<br>});</pre><h3>Summary</h3><ul><li>Sharing queries across components — use <strong>Query Objects</strong></li><li>Data transformation — the <strong>select option</strong> to the rescue!</li><li>Conditionally suppressing queries — try the “<strong>enabled</strong>” flag</li></ul><p>Putting this together, I’ve created a Sandbox you can play with:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fxd9mt&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fxd9mt&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fxd9mt%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/1243e5a54bc1ae22ca132091213fec75/href">https://medium.com/media/1243e5a54bc1ae22ca132091213fec75/href</a></iframe><p>Hope this helps and I’m really interested in hearing your experiences with React Query and any hints and tips you have!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3b0c98d77df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Example Typescript Refactor]]></title>
            <link>https://steven-hankin.medium.com/example-typescript-refactor-43ee80e6004d?source=rss-3f95198a309e------2</link>
            <guid isPermaLink="false">https://medium.com/p/43ee80e6004d</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[refactor]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Steve Hankin]]></dc:creator>
            <pubDate>Wed, 30 Dec 2020 17:24:18 GMT</pubDate>
            <atom:updated>2020-12-30T17:24:18.602Z</atom:updated>
            <content:encoded><![CDATA[<h4>Walkthrough of a code simplification of a contrived React app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIdEZbrSW5xHJ355OyOI8g.jpeg" /><figcaption>Photo by Benjamin Rascoe on Unsplash</figcaption></figure><p>When there is a need to improve code without changing its behaviour, the undertaking is called “Refactoring”. When we say improve, we essentially mean simplify in this context.</p><p>I’m going to show an example refactor of some code that typically happens on a second-pass of working code.</p><p>Let’s start with a simple React app that downloads a bunch of TODOs from a REST Service, sorts by name and lists them:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjolly-pike-4bc1z%3Ffile%3D%2Fsrc%2FApp.tsx&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjolly-pike-4bc1z%3Ffile%3D%2Fsrc%2FApp.tsx&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F4bc1z%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/02ab65495f526176494ff97ade383157/href">https://medium.com/media/02ab65495f526176494ff97ade383157/href</a></iframe><p>It’s a simple application that “works” and might not immediately appear too offensive (i.e. smelly code), but there are some improvements we can make here.</p><h3>Use built-in methods</h3><p>Firstly, I’ve included a sort function that really isn’t necessary since the String prototype in Javascript has a function that will do the same thing… only better. It’s called <strong>localecompare</strong></p><p>So we can rewrite as follows:</p><pre>todos.sort((a, b) =&gt; a.title.localeCompare(b.title))</pre><p>But even though it’s a nice compact arrow function and using a core method, this is not really expressing the intention very well.</p><p>The sort function accepts a “Compare Function” which we can extract and give an appropriate name:</p><pre>const compareTitle = <br>          (a: Todo, b: Todo) =&gt; a.title.localeCompare(b.title);</pre><pre>todos.sort(compareTitle)</pre><p>The compare function doesn’t really need to be inside the Todo List App component and can be extracted, along with the Todo type. For now they can just be placed above the component since it helps having the code in one place for readability, but eventually we will extract it into a separate module.</p><h3>Reduce operations</h3><p>The render function is still returning too much work; it will sort the list <em>on every render</em>. If this were a long list of large objects, it could impact performance, although we’d normally want to avoid rendering long lists and use approaches such as pagination.</p><p>Additionally, the Javascript sort function <em>mutates</em> the original array, which we definitely don’t want to do (React gets very upset if you change it’s state without it knowing).</p><p>Let’s perform the sorting only after we retrieve the data from the REST Service and before we store it in the state:</p><pre>.then((response) =&gt; response.json())</pre><pre>.then((_todos: Todo[]) =&gt; {</pre><pre>   setTodos(_todos.sort(compareTitle));</pre><pre>});</pre><p>This is a bit safer, since we’re mutating an array that is scoped to our XHR function and is not part of the React State. Also, we’re now only performing the sort operation once rather than on each render.</p><h3>Extract methods</h3><p>But this has made the useEffect() function rather busy.</p><p>We can extract the logic for retrieving Todos as a function (again moving it outside the component):</p><pre>const getSortedTodos = (): Promise&lt;Todo[]&gt; =&gt;</pre><pre>fetch(&quot;https://jsonplaceholder.typicode.com/todos&quot;)</pre><pre>   .then((response) =&gt; response.json())</pre><pre>   .then((todos: Todo[]) =&gt; {</pre><pre>      return todos.sort(compareTitle);</pre><pre>});</pre><p>…yielding a tighter Effect:</p><pre>useEffect(() =&gt; {</pre><pre>   getSortedTodos().then((sortedTodos) =&gt; setTodos(sortedTodos));</pre><pre>});</pre><p>⚠️ Note that we can’t remove the curly brackets, as tempting as it is to do so. This is because if an Effect returns something, it’s assumed to be a tidy-up function (which it won’t be in this case)</p><h3>Unwrap functions</h3><p>There is something we can do here to simplify the effect further. Notice that we are supplying a function that takes a sorted todo list and supplies it to the state setter. In this case, we are wrapping a function in a function for no additional benefit.</p><p>Instead, let’s supply just the setter function:</p><pre>useEffect(() =&gt; {</pre><pre>   getSortedTodos().then(setTodos);</pre><pre>}, []);</pre><h3>Modularize</h3><p>All the code that I’ve extracted from the component is now squirrelled away into a separate module called “todo.ts” and we have achieved a simplified version of the code without changing the behaviour.</p><p>Final version is here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UMELYiozcn-b4EJPNKY0w.png" /><figcaption>Woohoo! Same result, but easier to reason about..</figcaption></figure><p><a href="https://codesandbox.io/s/todo-list-8t02e?fontsize=14&amp;hidenavigation=1&amp;theme=dark">https://codesandbox.io/s/todo-list-8t02e?fontsize=14&amp;theme=dark</a></p><h3><strong>Recap</strong></h3><p>So we had a look at…</p><ul><li>using built-ins (swapping out homegrown functions for prototype methods)</li><li>reducing operations (by calling functions in the correct place)</li><li>extracted a method (with a useful name)</li><li>unwrapped a function</li><li>extracted the TODO code into a module.</li></ul><p>Feedback and comments welcome 👏🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43ee80e6004d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>