<?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 Taylor Mclean on Medium]]></title>
        <description><![CDATA[Stories by Taylor Mclean on Medium]]></description>
        <link>https://medium.com/@taylormclean15?source=rss-10c682281b0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*31oPdItay6bBgHmEUFvXmg.jpeg</url>
            <title>Stories by Taylor Mclean on Medium</title>
            <link>https://medium.com/@taylormclean15?source=rss-10c682281b0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:22:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@taylormclean15/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[Why you should be making use of leading indicators in your life]]></title>
            <link>https://medium.com/@taylormclean15/why-you-should-be-making-use-of-leading-indicators-in-your-life-f876684f78cf?source=rss-10c682281b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f876684f78cf</guid>
            <category><![CDATA[deep-work]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[habit-building]]></category>
            <category><![CDATA[personal-development]]></category>
            <dc:creator><![CDATA[Taylor Mclean]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 15:22:28 GMT</pubDate>
            <atom:updated>2022-01-15T15:22:28.523Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the more useful concepts in Cal Newport’s book <em>Deep Work</em> is the idea that you should use lead indicators to measure success. The concept comes from economics, but I think it can be applied more broadly. Cal Newport thought so too, as he brought up the concept to lend to his argument that it can be useful to treat ourselves like a business that we’re the CEO of.</p><p>Often we focus on lagging indicators, the ultimate outcome that we are aiming to achieve. However, such indicators don’t provide useful feedback in a timely fashion. When we are aiming to achieve an outcome, it’s best that we focus on the <em>process</em>. For example, if our goal is to read 5 books this month, the lagging indicator would be the number of books we have read so far this month. But this metric doesn’t inform us on more granular time scales — say, days — whether we’re sticking to our process of achieving that goal. If instead we use a leading indicator, such as number of consecutive days that we read a chapter of a book in the morning after coffee, this metric is more actionable. It forces us to directly face whether we are on track or not, and to focus on the process; what it looks like on a daily basis to read 5 books in a month.</p><p>I believe this concept can be stretched. We can think of <em>habits </em>as a leading indicator for the underlying goals they’re serving. Cultivating a habit of meal prepping on sundays so you’re less inclined to eat out during the week may be serving multiple goals: saving money, eating healthier, improving your cooking skills. Tracking this habit thus provides a useful metric for your goals of saving money, eating healthier, and improving your cooking skills. When you have a goal that will require sustained effort over a long time period, habits are your best leading indicator. They are process-focused. They keep us on track, and allow us to more clearly see the daily realities of achieving our long-term goals.</p><p>Stretching the concept even further, it can be a useful framework for many situations as you go about your day. Interpersonal communication, for example. If you’re at a social gathering and you’d like to veer outside of your comfort zone more than you normally do, the lagging indicator is… probably not something we can easily define, though what we’re ultimately seeking is the experience of conversations flowing effortlessly. If the lagging indicator is that experience, the leading indicator could be how many thought-provoking questions you can ask someone you’re interested in conversing with. If you’re looking to spend more quality time with your partner, the lagging indicator would be the experience of having spent a great weekend together, and the leading indicator could be to come up with interesting plans for the weekend that would be intimate or collaborative in nature.</p><p>We can stretch the concept into many domains, though the idea will be the same: if you focus on process over outcome, you will be more informed in moving in the direction you want to go. Leading and lagging indicators provide a helpful conceptual framework for understanding why, and a practical way to do so.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f876684f78cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I read the same three books every year]]></title>
            <link>https://medium.com/@taylormclean15/why-i-read-the-same-three-books-every-year-d56beb32ef58?source=rss-10c682281b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d56beb32ef58</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[new-years-resolutions]]></category>
            <dc:creator><![CDATA[Taylor Mclean]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 20:31:51 GMT</pubDate>
            <atom:updated>2021-12-31T20:31:51.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n3oqb502bQ5G6SYE" /><figcaption>Photo by <a href="https://unsplash.com/@christinhumephoto?utm_source=medium&amp;utm_medium=referral">Christin Hume</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are three books I tend to revisit at least once every year: <em>Flow: The Psychology of Optimal Experience</em> by Mihaly Csikszentmihalyi, <em>Deep Work: Rules for Focused Success in a Distracted World</em> by Cal Newport, and <em>Zen and the Art of Motorcycle Maintenance</em> by Robert Pirsig.</p><p>Rereading books is not a particularly uncommon practice. People reread books because they immensely enjoyed the first pass through, or they want to gain more insight in the second pass, or perhaps they’re just referencing a particular section. I’ve come across another reason to reread books that has become quite useful in my own life: as a course correction.</p><p>There are some books that tend to have a lasting impression on me. They contain lessons that resonate with me, and that I aspire to apply to my life. The books mentioned above are three of such books. My intention for this article is not to advocate for these books in particular, but instead to suggest the value that rereading this kind of book can have.</p><p>A second pass through a book can give the reader fresh insights they didn’t have on the first pass. Subsequent passes through a book, especially if it’s a dense read, can continue to provide fresh insights, but there reaches a point where there are diminishing returns. However, if a book contains lessons and insights that resonate with you, I argue that there’s value in simply re-exposing yourself to them. At this point, I’ve read the above books each at least 3–5 times. I’ve become quite familiar with their contents, the arguments made (or the stories told), and fresh passes through the book tend to not provide any significant insights that I haven’t already had. And while I quite enjoy reading each of the books in themselves, I think the novelty of fresh ideas in a new book would probably trump the enjoyment I get from their rereading.</p><p>If there is a lesson or insight that you want to apply to your life, it is not a one time effort. You must deliberate on what the lesson means in the context of your life, how you can make it fit, and how you can ensure that the subsequent changes you make will be sustained over the long term. For your changes to be sustained over the long term, you must continue to revisit the lesson periodically, and assess whether A) you are still effectively practicing the changes you put in place and B) whether those changes are having the desired effect. Often, revisiting a lesson or insight is enough to provide the gentle nudge you needed to reinvigorate the changes you may have let fall to the wayside. Sometimes, you just needed to hone your efforts a little. Other times, you may realize that the changes are not having the desired effect, or don’t in fact align with the original insight.</p><p>Rereading books with such lessons is a great way to revisit them, and to deliberate on how things are going. Reading aside, I think there is a deeper takeaway here. We should deliberate on important lessons more regularly. If a lesson or insight is truly important to us, we should want our minds to marinate in it frequently. It’s very easy to lose sight of what’s important if we don’t keep it top of mind. In the words of Ralph Waldo Emerson, <em>you become what you think about all day long.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d56beb32ef58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developer experience working with full-stack Typescript/Javascript/Node.js]]></title>
            <link>https://medium.com/@taylormclean15/developer-experience-working-with-full-stack-typescript-javascript-node-js-6621bbc30e26?source=rss-10c682281b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6621bbc30e26</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[full-stack-development]]></category>
            <dc:creator><![CDATA[Taylor Mclean]]></dc:creator>
            <pubDate>Sun, 28 Nov 2021 18:59:23 GMT</pubDate>
            <atom:updated>2021-11-28T18:59:23.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U38CMw2Ig6QHimXH" /><figcaption>Photo by <a href="https://unsplash.com/@karlp?utm_source=medium&amp;utm_medium=referral">Karl Pawlowicz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Having used JavaScript and Typescript as a full-stack developer for nearing two years, I’ve been reflecting on how the developer experience has been working in the JS/TS/Node.js ecosystem. In this article, I’ll go over the things I’ve really enjoyed, and the pain points I’ve felt.</p><h3>Pros:</h3><p><strong>Same language across the stack</strong></p><p>Many of the pros come from the ability to use the same language on the frontend and backend. It allows for more knowledge transfer across the stack, and less context-switching. For teams, it also means less specialization is needed, as everyone is working with the same tools.</p><p><strong>Isomorphic code</strong></p><p>Reusing code is great. If you use Typescript, you can share types across your frontend and backend. This is probably hands-down my favourite aspect of using Typescript full-stack. You can model your domain with Typescript types, and your backend can use these types for typing requests, responses, database schemas, etc., while your frontend can type the data returned by your backend, and the data it sends in requests. Since they’re sharing types, you reduce duplication, and you also keep your types in sync for free. When you use a different language on the backend, you need two sets of types, and especially if you have different developers or teams working on the frontend and backend, if the backend team decides to update the API, it’s more difficult to ensure that no client code is broken as a result.</p><p>In addition to sharing types, being able to share utility functions, business logic, etc., is also great. For example, in the project I’m currently working on, we’re able to share validation schemas between the frontend and backend. This allows us to validate forms on the frontend, and request bodies on the backend, using the exact same validation logic. We haven’t thrown a 422 in some time, and we’re given the confidence that any errors in the form can be displayed to the user before submitting a request to our backend. As another example, we display calculated values to users on the frontend based on their inputs in real time, before they’ve submitted the form. The same calculations are needed on the backend, so we were able to share these functions across the stack.</p><p><strong>Allows for multiple programming paradigms</strong></p><p>JavaScript has features that allow for both object-oriented and functional programming. While it’s generally good to maintain a consistent programming style across a codebase, certain paradigms make sense in different situations. For example, if you use React hooks on the frontend, you can employ a more functional style, whereas object-oriented programming is often a nice paradigm when modelling your domain on the backend. Having the flexibility is nice, as opposed to having to force your project to fit a style based on the language used.</p><p><strong>Syntax</strong></p><p>The syntax is Java-like, so it feels relatively familiar from the hop. JavaScript provides a fair bit of syntactical sugar, so you can be concise and accomplish a lot with a relatively small about of code, without losing too much on readability. I find it provides the syntactical simplicity of languages like Python, while sharing a fair bit in common with many other popular languages (Java, C#, C, C++, etc.).</p><p><strong>Elegant handling of asynchronicity</strong></p><p>As the web is inherently asynchronous, the handling of asynchronicity in JavaScript is top-notch. The syntax has improved over time, from using event callbacks, to promise chaining, to async/await. It takes some time to wrap your head around the mental model necessary to use async/await properly, though asynchronicity is inherently complex, and JavaScript provides a nice abstraction to make it as easy as possible.</p><p><strong>Simple architecture</strong></p><p><strong>JavaScript</strong> is by default single-threaded, which makes it easier to reason about. On the backend, the Node.js community generally favours performing parallel processing in a separate node/service, though it does have support for multithreaded programming via the `child_process` standard library. You can get into trouble if you block the main thread with a CPU-intensive process, though in general I’ve found the simple architecture of Node.js to make deploying, debugging, and reasoning about my apps easier. If you have a CPU-intensive workload, Node.js may not be the best option, but for many CRUD-based web apps, this is not a problem.</p><p>The event-driven architecture of Node.js also fits well with the request-response model of HTTP communication. The HTTP server from the standard library is simply an event emitter, that can emit events based on requests coming in. You can then have handlers listening to and responding to those events. It’s a very simple architecture that feels intuitive in a web context.</p><p><strong>Open-source community</strong></p><p><strong>JavaScript</strong> has a strong open-source community. I can generally find a well-supported package for most of my needs, which saves me from spending time on developing in-house solutions, and allows me to focus on more interesting problems. Developing with JavaScript feels very productive in this way.</p><p>I often see the criticism that there is a lot of “churn” in the JavaScript community, i.e., projects come and go, and the community doesn’t seem to settle on libraries. This may have been an issue in the past, but as of 2021, there does seem to be a stable set of libraries that the community has settled on, at least for professional projects. Some examples: For the frontend, you’ll mostly see Angular, React, or Vue. For the backend, you’ll see Express, Nest.js, Fastify, or Koa. For database ORM’s, you’ll see TypeORM, Sequelize, Mongoose, or Knex.js. For validation, you’ll see Joi, Yup, or Zod. For an HTTP client, you’ll see axios or node-fetch. In short, I don’t think the churn argument is as applicable anymore.</p><p>Along with a strong open-source community has come a widespread adoption across the industry. This has resulted in many services and software vendors providing first-class support for the JavaScript language. If you’re looking for an SDK, you can be sure that if one exists, there will be one for JavaScript. If you’re looking to use a platform-as-a-service (PaaS), you can be sure that most vendors will provide support for JavaScript/Node.js. This has made reaching out and using services and tools hassle-free.</p><p><strong>First-class support for JSON</strong></p><p>As JSON is the preferred data format of the web, it’s nice to use a language where it feels very much baked-in. There’s no need for complicated serialization, as JSON maps directly to JavaScript objects. This makes data handling for web applications very intuitive with JavaScript.</p><h3>Cons:</h3><p><strong>Complicated tooling</strong></p><p>Some of the tooling around Javascript has become quite complicated. I think this is mostly due to the fact that Javascript is run in so many different environments that support different features of the language and have different usage requirements and resource constraints. Not to mention the chaos of the module system, where there are several competing standards, and you’re often left needing to convert between one or the other. It’s clear that Javascript as a language is trying to support many different use-cases, which is a problem that most other backend languages don’t have. I’ve been playing with Golang recently, and the simplicity of the toolchain is enviable compared to Javascript. Keep in mind for perspective as you read the next few paragraphs that the equivalent in Golang is “go build”.</p><p>For the frontend, you’ll want to bundle your assets using something like Webpack. You may also need to transpile your code to an earlier ECMAScript version with Babel if you’re supporting older browsers. If you’re using React, you’d also need to transform your JSX to JS. If you’re using Typescript, you need to compile your TS to JS. You may also get into code-splitting and other build customizations, which can throw you deep down the Webpack rabbit-hole.</p><p>The frontend build and bundle process alone is complicated, but I don’t want to focus on it too much, since there’s really no way around the use of Javascript at the moment if you’re building a moderately complex web application.The backend build process is generally a bit more straightforward, but not by much. You generally wouldn’t have much use for transpilation to earlier ECMAScript versions, since you have control over what environment your server code will run in. However, it’s fairly common to bundle your Node.js server with the Typescript CLI build tool, or with Webpack (or other less popular tools).</p><p>Configuring a Typescript build can be a nightmare. There are countless compiler options to handle every use-case imaginable. While it’s nice to have the flexibility to customize your build, the complexity this brings in my experience has been more of an impediment than a benefit.</p><p><strong>Tooling can be slow</strong></p><p>Javascript is a reasonably fast language for it’s use-cases, but it wouldn’t be my first option for writing important development tools. Nonetheless, naturally most of the tooling in the Javascript/Typescript/Node.js community has been built with Node.js. This includes popular tools like Webpack, Babel, ESLint, TSC, Jest, JSDOM, etc. These are all tools that most Javascript codebases in the wild will make use of, and they’re quite slow in my experience.</p><p>Building a medium-sized Node.js server app with Webpack usually takes over 30 seconds. This adds up if you intend to run your build in CI. There have been efforts to improve the build tooling with projects like ESBuild (<a href="https://github.com/evanw/esbuild">https://github.com/evanw/esbuild</a>) that is written in Golang. The trend of bringing systems languages in to build Javascript tooling could greatly improve the situation, but we may be a year or two out until they see widespread adoption. Webpack, Babel, TSC, etc. are heavily baked into the ecosystem at this point.</p><p><strong>Language quirks</strong></p><p>Javascript is famously a fairly quirky language. Things like `typeof null === “object”` stand out in my mind. It has generally been improving over time, but some quirks have been left in the language to maintain backwards compatibility. In all honesty, the quirks haven’t come into play too much in my experience. But you do run into occasional weirdness that can be difficult to debug if you don’t know what you’re looking for.</p><p>With Typescript, since it is a superset of Javascript and compiles to Javascript, it must maintain compatibility with the quirks of Javascript and bend it’s behaviour to accommodate. I’ve come across some really weird behaviour in Typescript because of this. Here is an example: <a href="https://github.com/microsoft/TypeScript/issues/46927">https://github.com/microsoft/TypeScript/issues/46927</a>. Trying to type a dynamic language is inherently difficult, and is not perfect. So even while using Typescript you don’t ever feel like you’re getting complete type safety.</p><h3>Conclusion</h3><p>In general I’ve found Javascript/Typescript to be a great language and ecosystem to build full stack web applications in. It fits most use-cases pretty well. Where I might not recommend it is for applications where:</p><ul><li>Performance is paramount</li><li>The workload is CPU-intensive</li><li>The codebase will become large, with many developers/multiple teams. The slow tooling can be an impediment (at least for now, until it improves).</li></ul><p>Hope you found this helpful! You can find me on linkedin at <a href="https://www.linkedin.com/in/taylormclean/">https://www.linkedin.com/in/taylormclean/</a>. Feel free to reach out if you have any questions, or want to chat.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6621bbc30e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why our team switched from Yup to Zod for validation]]></title>
            <link>https://medium.com/@taylormclean15/why-our-team-switched-from-yup-to-zod-for-validation-9b46d8b17183?source=rss-10c682281b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b46d8b17183</guid>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[isomorphic-javascript]]></category>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[yup]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Taylor Mclean]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 01:47:33 GMT</pubDate>
            <atom:updated>2021-11-14T01:47:33.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JTH5VP4HyKY4_spv" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Our team at Gyroscopic (<a href="https://www.linkedin.com/company/gyroscopic/">https://www.linkedin.com/company/gyroscopic/</a>) is developing a web application, using React on the frontend and Node (Nest.js) on the backend. Our application consists of many complicated forms, and because of this, we rely heavily on validation libraries to integrate with our forms and REST API’s. We’ve tested out a few validation libraries in search for one that would fit our needs. Over time we’ve refined our criteria for the features we need. Here is our current criteria:</p><ul><li>The project is well-supported. As it will be an integral dependency in our application, we’d like to choose a library that has a healthy open-source community to ensure we can depend on it.</li><li>It supports complex validation logic, including dynamic validation, casting, and transformations.</li><li>It’s composable, i.e. it has support for things like union/intersection schemas, etc.</li><li>It integrates well with React Hook Form (<a href="https://github.com/react-hook-form/react-hook-form">https://github.com/react-hook-form/react-hook-form</a>). We use this library extensively for developing complex dynamic forms, and it provides the ability to plug-and-play with some of the popular validation libraries.</li><li>It has an API for dynamically translating error messages and hooking into our internationalization libraries. This one is especially important, as our application must support multiple languages, and our forms render error messages generated from validations.</li><li>It has static type inference.</li></ul><p>Initially we used Joi (<a href="https://github.com/sideway/joi">https://github.com/sideway/joi</a>) for basic validations, as it has probably the strongest community of the popular validation libraries. As our codebase evolved, we realized that the last criteria — static type inference — was a critical feature for us. We use Typescript on both the frontend and backend, and this allows us to leverage isomorphic code, including sharing types between the client and server, as well as validation schemas. This is a great setup, as our frontend forms and backend REST API’s easily remain in sync. However, without static type inference, our Typescript types and validation schemas could become out of sync, and this could cause a whole class of bugs that we’d like to avoid. Ideally we could infer the types defined by our validation schemas, and enjoy the type safety provided by using these types when passing around data in our app.</p><p>Joi did not have any type inference capabilities, so we switched over to Yup. All seemed great, it also had a strong community and ticked off all of our criteria. However we began to notice some peculiarities in how Yup was inferring the types from our schemas. I’ll just jump right into some code examples to illustrate this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/011160bffccd19d3143c552c30a8ec39/href">https://medium.com/media/011160bffccd19d3143c552c30a8ec39/href</a></iframe><p>As you can see, once you have any nested fields in your schema, Yup’s type inference is simply incorrect. This caused us a lot of headaches in our codebase. The type errors we were getting were gibberish. Here is the type error you would get from the above code:</p><pre>Property &#39;object&#39; is missing in type &#39;{ number: number; string: string; }&#39; but required in type &#39;AssertsShape&lt;{ number: RequiredNumberSchema&lt;number | undefined, AnyObject&gt;; string: RequiredStringSchema&lt;string | undefined, AnyObject&gt;; object: OptionalObjectSchema&lt;{ number: NumberSchema&lt;number | undefined, AnyObject, number | undefined&gt;; string: StringSchema&lt;string | undefined, AnyObject, string | undefined&gt;; }, AnyObject, TypeOfShape&lt;{ number: NumberSchema&lt;number | undefined, AnyObject, number | undefined&gt;; string: StringSchema&lt;string | undefined, AnyObject, string | undefined&gt;; }&gt;&gt;; }&gt;&#39;</pre><p>In essence, the type of an optional field resolves to field: &lt;type&gt; | undefined rather than field?: &lt;type&gt; | undefined. This means that you need to explicitly set all optional fields to undefined if omitted.</p><p>This caused us enough grief that, although we had Yup tightly integrated into our codebase, we decided to shop around for libraries that provided better type inference, and eventually landed on Zod (<a href="https://github.com/colinhacks/zod">https://github.com/colinhacks/zod</a>). From our research, Zod provides the best static type inference in town, and was built with first-class support for Typescript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b46d8b17183" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating PDFs with React]]></title>
            <link>https://medium.com/@taylormclean15/generating-pdfs-with-react-f49787ed16c?source=rss-10c682281b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f49787ed16c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[generate-pdf]]></category>
            <category><![CDATA[pdf-react]]></category>
            <category><![CDATA[isomorphic-javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Taylor Mclean]]></dc:creator>
            <pubDate>Tue, 07 Sep 2021 11:48:08 GMT</pubDate>
            <atom:updated>2021-09-07T11:51:02.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5L33ZPcwdsdJoQg2" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=medium&amp;utm_medium=referral">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Generating PDFs is a common feature needed in many applications. Most popular programming languages tend to have established tooling and libraries that allow for generating PDFs programmatically. As a developer that makes heavy use of React, I prefer to remain in the React paradigm as much as possible, especially for projects whose frontends are predominantly (or entirely) written in React, to reduce context switching and also to make the codebase more cohesive and reusable. That’s why my initial instinct was to scan the React open-source landscape when I had to develop a PDF generation service for the React-heavy project I’m working on. To my delight, there was some excellent tooling available. In the following article, I will outline some of the packages I used to build out this service.</p><p>I created an example project to compliment this article if you would like to see some code samples. You can find it at <a href="https://github.com/tmclean15/react-pdf-overview.">https://github.com/tmclean15/react-pdf-overview.</a></p><p><strong>React PDF (https://github.com/diegomura/react-pdf)</strong></p><p>This is an excellent package for creating PDFs with React. It provides several primitive components that you can use to compose your document. I’ll outline a few, though you can find full documentation for these at <a href="https://react-pdf.org/">https://react-pdf.org/</a>:</p><ul><li>Document: The root component of a document; can accept several props to provide metadata to PDF, and all child components should be page components.</li><li>Page: A page in the document (semantically). Pages can be set to wrap (i.e. span multiple pages in the file) or not.</li><li>View: The building block for templates and reusable components. Views can be nested within other views.</li><li>Image: Displays an image given a source. The source can be a network resource, a data buffer, or a filesystem path (only for Node).</li><li>Text: Displays text, fairly straightforward.</li><li>Link: Displays a hyperlink, again fairly straightforward.</li><li>Canvas: Provides an API for drawing custom content in the PDF. This is especially useful if you need to draw particular shapes, and would prefer to not need an image.</li></ul><p>Using these primitives, you can compose your document. For styling, you can create CSS-in-JS stylesheets that are reminiscent of Material UI styling. The documentation provides a list of valid CSS properties that can be used. Not all CSS properties are supported, but most of the main ones are, including flexbox. You can use media queries to make your document templates more responsive. The package also comes with a font module, that allows you to load and register fonts from different sources.</p><p>The main benefit of this package, in my opinion, is the ability to use it in the browser and on the server with Node. This allows you to share document templates across your stack, and leverage the isomorphism that we’ve all come to love with JavaScript. In the project I’m currently working on, we leverage this to provide a document preview functionality in our web client while keeping our PDF generation service on the server and allowing our other services and clients to generate and download identical reports.</p><p>With React PDF, generating a report with a simple straightforward layout is a breeze. However, if you want to render more complicated layouts, things become somewhat cumbersome. For my use case, I required the ability to render tables and charts in my documents. I found a few packages and workarounds to make this possible.</p><p><strong>React PDF Table (</strong><a href="https://github.com/dmk99/react-pdf-table"><strong>https://github.com/dmk99/react-pdf-table</strong></a><strong>)</strong></p><p>This package is intended to work with React PDF and provides components for easily adding a table to your document. You could probably build a similar table component in-house without too much trouble, but it’d require a fair bit of CSS fandangling, and in my case, I preferred to use an off-the-shelf solution and get back to writing business differentiating code.</p><p><strong>Chart.js (</strong><a href="https://github.com/chartjs/Chart.js"><strong>https://github.com/chartjs/Chart.js</strong></a><strong>)</strong></p><p>For creating charts in JavaScript, Chart.js is the definitive package. When looking into how I could add charts to my PDF documents, my first thought was whether I could simply embed an image of a chart generated from Chart.js using the image component from React PDF. This is what I ended up doing, and it works great. The minor tradeoff to this approach is that images are somewhat large relative to a chart built with the React PDF canvas API (which uses pdfkit under the hood), though the size of the resulting PDF files was small enough that I didn’t feel the need to optimize any further.</p><p>The caveat to using Chart.js is that it requires the use of the browser’s canvas API, therefore it will not work out of the box when trying to generate PDFs on the server. Luckily there are some workarounds to this.</p><p><strong>Chart.js Node Canvas (</strong><a href="https://github.com/SeanSobey/ChartjsNodeCanvas"><strong>https://github.com/SeanSobey/ChartjsNodeCanvas</strong></a><strong>)</strong></p><p>As the name suggests, this package provides a canvas-like API that emulates the browser canvas API and integrates seamlessly with Chart.js. It’s built on top of Node Canvas (<a href="https://github.com/Automattic/node-canvas">https://github.com/Automattic/node-canvas</a>), and according to the README, “is an implementation of the Web Canvas API and implements that API as closely as possible”. With this package, it was very simple to get Chart.js up and running on the server. It provides a method to render the chart to a buffer, that React PDF can then use as the source of its image component.</p><p>Using these packages should get you 90% of the way there in generating PDFs for most applications that use React on the frontend and Node for the backend. For the other 10%, the React PDF API is robust enough to build any custom solution you need, especially with the canvas API. Keeping with the React component paradigm, you can create modular components for your PDFs that you’ll be able to use across your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f49787ed16c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jest testing — mocking child components to make your unit tests more concise]]></title>
            <link>https://medium.com/@taylormclean15/jest-testing-mocking-child-components-to-make-your-unit-tests-more-concise-18691ef6a0c2?source=rss-10c682281b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/18691ef6a0c2</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Taylor Mclean]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 01:41:55 GMT</pubDate>
            <atom:updated>2021-08-04T01:41:55.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jest testing — mocking child components to make your unit tests more concise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PqlaD51FRHK-t9Hw" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Due to the tree-like structure of components in a React application, it’s common that components higher up in the tree can become more difficult to test, owing to the fact that they may be comprised of multiple complex child components. Testing such components may require you to perform a number of interactions on the child components to “set the stage”, and since you may already have unit tests for the child components, you don’t want to have to retest their functionality. What can you do?</p><p>The first thing to note is that you may actually be wanting to interact with the child components, in order to test the full integration of the logic of the parent component with all of the child components. However, if you’re looking to unit test just the logic contained in the parent component, you’ll want to abstract away the functionality of the child components.</p><p>With Jest, you can mock entire React components, and this is a great pattern for tackling the above problem.</p><p>Let’s say we have a parent component that contains a bunch of logic and functionality that we’d like to test:</p><pre>import React, { useState } from &quot;react&quot;;<br>import UserManagement from &quot;./child-component&quot;;<br><br>const GroupForm = ({ initialUsers = [] }) =&gt; {<br>  const [users, setUsers] = useState(initialUsers);<br><br>  const addUser = (newUser) =&gt; setUsers([...users, newUser]);<br><br>  const deleteUser = (index) =&gt; {<br>    const updatedUsers = [...users];<br>    updatedUsers.splice(index, 1);<br>    setUsers(updatedUsers);<br>  };<br><br>  const editUser = (index, editedUser) =&gt; {<br>    const updatedUsers = [...users];<br>    updatedUsers[index] = editedUser;<br>    setUsers(updatedUsers);<br>  };<br><br>  const handleSubmit = (event) =&gt; {<br>    // send a request to create a group with the given users<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;label htmlFor=&quot;groupName&quot;&gt;Group Name&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; id=&quot;groupName&quot; name=&quot;groupName&quot; /&gt;<br><br>        &lt;label htmlFor=&quot;date&quot;&gt;Date&lt;/label&gt;<br>        &lt;input type=&quot;date&quot; id=&quot;date&quot; name=&quot;date&quot; /&gt;<br><br>        &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/form&gt;<br>      &lt;UserManagement<br>        users={users}<br>        onAdd={addUser}<br>        onDelete={deleteUser}<br>        onEdit={editUser}<br>      /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default GroupForm;</pre><p>Here is the child component:</p><pre>import React, { useState } from &quot;react&quot;;<br><br>const UserForm = ({ user, onSubmit }) =&gt; {<br>  const [name, setName] = useState(user.name ?? &quot;&quot;);<br>  const [address, setAddress] = useState(user.address ?? &quot;&quot;);<br><br>  const handleSubmit = (event) =&gt; {<br>    event.preventDefault();<br>    event.preventPropagation();<br><br>    onSubmit({<br>      name,<br>      address,<br>    });<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;label htmlFor=&quot;name&quot;&gt;Name&lt;/label&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        id=&quot;name&quot;<br>        name=&quot;name&quot;<br>        value={name}<br>        onChange={(event) =&gt; setName(event.target.value)}<br>      /&gt;<br><br>      &lt;label htmlFor=&quot;address&quot;&gt;Address&lt;/label&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        id=&quot;address&quot;<br>        name=&quot;address&quot;<br>        value={address}<br>        onChange={(event) =&gt; setAddress(event.target.value)}<br>      /&gt;<br><br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>const UserManagement = ({ users, onAdd, onDelete, onEdit }) =&gt; {<br>  const [formOpen, setFormOpen] = useState(false);<br>  const [selectedUser, setSelectedUser] = useState(null);<br><br>  const Form = () =&gt; {<br>    if (formOpen) {<br>      if (selectedUser) return &lt;UserForm onSubmit={editUser} user={{}} /&gt;;<br>      else return &lt;UserForm onSubmit={addUser} user={user[selectedUser]} /&gt;;<br>    }<br>    return null;<br>  };<br><br>  const addUser = (data) =&gt; {<br>    onAdd(data);<br>    setFormOpen(false);<br>  };<br><br>  const editUser = (data) =&gt; {<br>    onEdit(selectedUser, data);<br>    setSelectedUser(null);<br>    setFormOpen(false);<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={() =&gt; setFormOpen(true)}&gt;Add user&lt;/button&gt;<br>      &lt;table&gt;<br>        &lt;thead&gt;<br>          &lt;tr&gt;Name&lt;/tr&gt;<br>          &lt;tr&gt;Address&lt;/tr&gt;<br>          &lt;tr&gt;Action&lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>          {users.map((user, index) =&gt; (<br>            &lt;tr&gt;<br>              &lt;td&gt;{user.name}&lt;/td&gt;<br>              &lt;td&gt;{user.address}&lt;/td&gt;<br>              &lt;td&gt;<br>                &lt;button<br>                  onClick={() =&gt; {<br>                    setSelectedUser(index);<br>                    setFormOpen(true);<br>                  }}<br>                &gt;<br>                  Edit<br>                &lt;/button&gt;<br>                &lt;button onClick={() =&gt; onDelete(index)}&gt;Delete&lt;/button&gt;<br>              &lt;/td&gt;<br>            &lt;/tr&gt;<br>          ))}<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>      &lt;Form /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default UserManagement;</pre><p>To summarize what’s going on: We have a parent component with a form for creating user groups, and a child component with a form and a table for managing users (adding, editing, deleting). The users state is ultimately managed by the parent component, and the idea is that when the user group is created, it’s created with the list of users.</p><p>Let’s assume that we already have unit tests for the child component. When testing the parent component, we would rather avoid all of the “ceremony” involved in interacting with the child component just to test the parent component. For example, we would have to open the user form, select the form inputs, fill them out, submit the form, and then test that the parent component handled the form submission correctly. Instead, we will mock the child component to be a simplified version that will make our tests considerably more concise.</p><pre>let mockUser;<br>let mockIndex;<br><br>jest.mock(&quot;./child-component&quot;, () =&gt; ({ onAdd, onDelete, onEdit, users }) =&gt; (<br>  &lt;div&gt;<br>    &lt;button onClick={() =&gt; onAdd(mockUser)} data-testid=&quot;addUser&quot;&gt;<br>      Add<br>    &lt;/button&gt;<br>    &lt;button<br>      onClick={() =&gt; onDelete(mockIndex, mockUser)}<br>      data-testid=&quot;deleteUser&quot;<br>    &gt;<br>      Delete<br>    &lt;/button&gt;<br>    &lt;button onClick={() =&gt; onEdit(mockIndex, mockUser)} data-testid=&quot;editUser&quot;&gt;<br>      Edit<br>    &lt;/button&gt;<br>    &lt;span data-testid=&quot;users&quot;&gt;{JSON.stringify(users)}&lt;/span&gt;<br>  &lt;/div&gt;<br>));</pre><p>We will also add a little test utility for quickly asserting that the users are being managed correctly.</p><pre>const assertUsers = (expectedUsers) =&gt; {<br>  const usersSpan = screen.getByTestId(&quot;users&quot;);<br>  const usersText = usersSpan.innerHTML;<br>  const actualUsers = JSON.parse(usersText);<br>  expect(expectedUsers).toEqual(actualUsers);<br>};</pre><p>Now notice how concise our tests can be.</p><pre>describe(&quot;GroupForm&quot;, () =&gt; {<br>  it(&quot;correctly handles adding a user&quot;, () =&gt; {<br>    mockUser = {<br>      name: &quot;test add user&quot;,<br>      address: &quot;test add user&quot;,<br>    };<br><br>    render(&lt;GroupForm /&gt;);<br><br>    const addUserButton = screen.getByTestId(&quot;addUser&quot;);<br>    userEvent.click(addUserButton);<br><br>    assertUsers([mockUser]);<br>  });<br><br>  it(&quot;correctly handles deleting a user&quot;, () =&gt; {<br>    mockIndex = 1;<br>    const initialUsers = [<br>      {<br>        name: &quot;1&quot;,<br>        address: &quot;1&quot;,<br>      },<br>      {<br>        name: &quot;2&quot;,<br>        address: &quot;2&quot;,<br>      },<br>      {<br>        name: &quot;3&quot;,<br>        address: &quot;3&quot;,<br>      },<br>    ];<br><br>    render(&lt;GroupForm initialUsers={initialUsers} /&gt;);<br><br>    const deleteUserButton = screen.getByTestId(&quot;deleteUser&quot;);<br>    userEvent.click(deleteUserButton);<br><br>    const expectedUsers = [initialUsers[0], initialUsers[2]];<br>    assertUsers(expectedUsers);<br>  });<br><br>  it(&quot;correctly handles editing a user&quot;, () =&gt; {<br>    mockIndex = 0;<br>    const initialUsers = [<br>      {<br>        name: &quot;initial&quot;,<br>        address: &quot;initial&quot;,<br>      },<br>    ];<br>    mockUser = {<br>      name: &quot;edited&quot;,<br>      address: &quot;edited&quot;,<br>    };<br><br>    render(&lt;GroupForm initialUsers={initialUsers} /&gt;);<br><br>    const editUserButton = screen.getByTestId(&quot;editUser&quot;);<br>    userEvent.click(editUserButton);<br><br>    assertUsers([mockUser]);<br>  });<br>});</pre><p>At this point, it’s prudent to make note of a few potential pitfalls:</p><p>If your mock component doesn’t accurately capture the functionality of the original component, your tests could give false positives. The mock component doesn’t necessarily need to emulate the entire functionality of the original component, but it does need to present the same API as the original. Generally speaking, this means it should take the same props, and use the same callbacks.</p><p>Your mock component may also become out of sync with the original component, and your unit tests may still pass. However, if you have good integration and end-to-end test coverage, any such discrepancies should be caught. Ultimately this is a shortcoming of unit tests in general, and is why it’s good to supplement your unit tests with integration and end-to-end tests.</p><p>In summary, when you are looking to avoid test coverage overlap/duplication, or looking to achieve more focused unit tests, the pattern of mocking child components can be a useful tool in your toolkit.</p><p>You can find the full code gist at <a href="https://gist.github.com/tmclean15/212bac0f1fe6277c9d79d42fe334f736">https://gist.github.com/tmclean15/212bac0f1fe6277c9d79d42fe334f736</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18691ef6a0c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep agreements with yourself, or explicitly renegotiate]]></title>
            <link>https://medium.com/@taylormclean15/keep-agreements-with-yourself-or-explicitly-renegotiate-44e943bb5a8e?source=rss-10c682281b0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/44e943bb5a8e</guid>
            <category><![CDATA[productivity-tips]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[getting-things-done]]></category>
            <dc:creator><![CDATA[Taylor Mclean]]></dc:creator>
            <pubDate>Sun, 01 Aug 2021 21:37:38 GMT</pubDate>
            <atom:updated>2021-08-01T21:37:38.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DanW-tmDINRzL6Q0QBo2NA.jpeg" /></figure><p>You are what you do, and what you do is a result of how you manage agreements with yourself.</p><p>We’ve all experienced the feelings of guilt and frustration after having broken a promise we made with ourselves. Whether it was a habit we were hoping to implement and didn’t execute, or an impulse we swore not to succumb to, or perhaps an item on the to-do list that we procrastinated on, breaking prior agreements that we made with ourselves over time can chip away at our confidence and sense of self-worth. Similar to how our perceptions of others can be worsened if they don’t follow through on their promises, this applies equally to ourselves but in subtler ways that can compound over time.</p><p>There’s a false perception that the repercussions of not following through on agreements with ourselves will be less severe than agreements with others, perhaps since we believe we will be more willing to take it easy on ourselves. While this may come somewhat down to disposition — some are harder on themselves than others — most people will feel some degree of guilt and frustration. These emotions may be fleeting, and may be less severe (in the immediate future) than getting fired from your job for not following through on a promise to your boss, for example, but the real repercussion is the incremental loss of confidence in your ability to follow through on your agreements. Over time, this may lead to putting less psychological weight on agreements you make with yourself, since the trust that you’ll follow through on the agreement is diminished, and thus the sanctity of the agreement is broken. Ultimately, if you can’t trust yourself, it will be very difficult to make progress in any domain.</p><p>The first key takeaway here is that <strong>breaking agreements with yourself will compound over time to diminish your ability to act purposefully toward desired outcomes.</strong></p><p>Agreements we make with others are often more explicitly stated than agreements that we make with ourselves. For example, “I’ll have the report to you by friday” is an agreement in no uncertain terms. There’s no ambiguity in whether the agreement is kept or broken. On the other hand, agreements we make with ourselves are often quite ambiguous. They may be a vague notion, e.g. “I should really get that report done at some point”, or they may be in a form that’s not clear as to whether the agreement was kept, e.g. “I’ll get the report done when I have time”. When agreements are ambiguous, they can still wear on the psyche, as we increasingly feel a building sense of having broken the agreement while not at any point knowing with full clarity that the agreement was in fact broken. This is a significant source of “open loops”, to use the popular lingo from David Allen’s <em>Getting Things Done.</em></p><p>The second takeaway is that <strong>agreements with yourself should be unambiguous and well-defined, so that there is no uncertainty as to whether the agreement was kept or broken.</strong></p><p>We also tend to manage our agreements with others with more care than we do agreements with ourselves. For example, if you know that you won’t be able to get the report done by 5pm as you told your boss you would, you’d likely email them to provide an update on why it took longer than you originally expected, and to renegotiate the agreement of when the report will get done. This process of explicitly renegotiating an agreement is something that we tend to apply less rigorously to ourselves. There may be no renegotiation at all, with a vague acceptance that we simply did not execute on the thing we told ourselves we would. Or we may try to clumsily or half-committedly renegotiate, e.g. “I didn’t work out today but I’ll make up for it at some point this week”.</p><p>Renegotiating is a normal part of managing agreements, as unexpected things may come up, or priorities may change, or the realities of the situation may be different than when the agreement was originally made. However, the renegotiation must be explicit otherwise the sanctity of the agreement will be lost, and the likelihood that we uphold the agreement will drop dramatically.</p><p>There are 2 options we have when renegotiating an agreement with ourselves:</p><ol><li><strong>Drop the agreement altogether.</strong> Perhaps our priorities have changed such that following through on the agreement no longer aligns with our goals, or perhaps following through on the agreement has proved to be more difficult or time-consuming than we had originally estimated, and it is now impacting other more important agreements. The important thing here is to be very explicit in dropping the agreement entirely; if you are not intending to renegotiate the agreement, it should not be left in a state where you’re only partially committed to the agreement.</li><li><strong>Change the terms of the agreement.</strong> Perhaps you had planned to get an hour of writing in this evening, but a close friend that you haven’t seen in a while was in town and wanted to grab a coffee. Understandably, you’d like to prioritize visiting with your friend, but don’t want to completely give up on the initial agreement you had with yourself to do some writing. You could change the terms of the agreement to instead wake up an hour earlier tomorrow morning and do the writing then. The new terms should be explicit and actionable, to leave no uncertainty as to whether the revised agreement is kept or not.</li></ol><p>Making and keeping agreements with ourselves is the primary mechanism of productivity and self-growth. Therefore, we should maintain these agreements with as much (if not more) care and vigor as we maintain agreements with others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44e943bb5a8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>