<?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 Miroslav Pillár on Medium]]></title>
        <description><![CDATA[Stories by Miroslav Pillár on Medium]]></description>
        <link>https://medium.com/@pillinho?source=rss-515feaa3ce20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*O19cBHb7CIy7WFijVPJuLw.jpeg</url>
            <title>Stories by Miroslav Pillár on Medium</title>
            <link>https://medium.com/@pillinho?source=rss-515feaa3ce20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:24:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pillinho/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[Internationalization (i18n) in React using hooks]]></title>
            <link>https://levelup.gitconnected.com/internationalization-i18n-in-react-using-hooks-62e1262c2c51?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/62e1262c2c51</guid>
            <category><![CDATA[international-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 14:57:21 GMT</pubDate>
            <atom:updated>2020-10-13T14:57:21.867Z</atom:updated>
            <content:encoded><![CDATA[<p>A step by step tutorial with i18next library and unit tests</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T7x7PxdFSftXADon" /><figcaption>Photo by <a href="https://unsplash.com/@unonueveochotres?utm_source=medium&amp;utm_medium=referral">1983 (steal my _ _ art)</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your client asks you to do that. I know, that could be pretty overwhelming, especially for less-experienced developers.</p><p>But, it isn&#39;t. Trust me.</p><p>I went through the same problem.</p><h3>What is this about</h3><p>Simply said, it&#39;s rather a time-consuming task than spending time on the logic itself.</p><p>But keep in mind, there should be two conditions, which your team would appreciate regarding i18n:</p><ul><li>Static texts should be stored in files by language, not within the code.</li><li>It must pass tests in the unit testing</li></ul><p>The first condition means it requires a lot of time. So here&#39;s a little advice: you&#39;d better start to store static texts in JSON files as soon as possible. And if i18n support would be demanded, you will just add a new translation file.</p><p>The second condition is pretty usual in most of the serious projects. You can learn more about <a href="https://levelup.gitconnected.com/how-to-write-unit-tests-with-react-testing-library-d9624fd2b707">unit testing with React Testing Library</a>.</p><p>Anyway, I’m going to show you how to handle such tasks within the React project using hooks as well as how to deal with texts in unit tests. We’re going to use one of the most popular i18n libraries, <a href="https://react.i18next.com/">react-i18next</a>.</p><p>I&#39;m going to implement internalization within my countries app, which you can <a href="https://github.com/Dromediansk/countries-app-blog/tree/i18n">clone from GitHub</a> or create a project by yourself.</p><h3>Let&#39;s configure</h3><p>Firstly, you need to install the library with its dependencies:</p><pre>npm install react-i18next i18next i18next-http-backend --save</pre><p>And also a <a href="https://github.com/i18next/i18next-browser-languageDetector">dependency for detecting the user language</a> in the browser (optional):</p><pre>npm install i18next-browser-languagedetector --save</pre><p>Now, create a new file i18n.js beside your index.js containing the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1a3b698e9314d72ef849d6f777ce499/href">https://medium.com/media/a1a3b698e9314d72ef849d6f777ce499/href</a></iframe><p>And then import the file in index.js:</p><pre>import React, { Component } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import App from &#39;./App&#39;;<br><strong>import &#39;./i18n&#39;;</strong></pre><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;root&quot;));</pre><ul><li>We&#39;re using the i18next library on top of our app,</li><li>using Backend to load the files from /public/locales folder (will be added in a moment),</li><li>passing i18n instance to react-i18next, which will make it available for all the component,</li><li>applying other configuration options with init(). Of course, you can <a href="https://www.i18next.com/overview/configuration-options">customize them with available options</a>.</li></ul><p>After you&#39;re done with the configuration, create a new folder locales in the public folder. Here we will store folders of every language. So inside locales, create another folder en (or any other language you want to use) and create a new file translation.json.</p><p>Here’s a complete structure with English and German:</p><pre>- public<br>    -- locales<br>        -- en<br>            -- translation.json<br>        -- de<br>            -- translation.json<br>- src</pre><h3>Practice time</h3><p>Let&#39;s have a simple representational component namedHome:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64c4c171b338eedfb4ca9a196c151f34/href">https://medium.com/media/64c4c171b338eedfb4ca9a196c151f34/href</a></iframe><p>This is just a regular landing page, in which we show three sentences. Now, according to the condition mentioned above, we should move these static texts into the JSON file.</p><p>So here&#39;s the English version:</p><pre>{<br>    &quot;welcome&quot;: &quot;Welcome&quot;,<br>    &quot;appAbout&quot;: &quot;In this app you can check basic data of all      countries in the world.&quot;,<br>    &quot;explore&quot;: &quot;Feel free to explore!&quot;<br>}</pre><p>And German version:</p><pre>{<br>    &quot;welcome&quot;: &quot;Willkommen&quot;,<br>    &quot;appAbout&quot;: &quot;In diesem App können Sie Grunddata der Länder   ansehen.&quot;,<br>    &quot;explore&quot;: &quot;Fühlen Sie sich frei zu erkunden!&quot;<br>}</pre><p>Keep in mind, that in every key-value pair, the key must be the same. It should be concise and descriptive because we&#39;ll use it in our codebase.</p><p>However, in big projects, I recommend separate texts based on sections, components, etc. (depends on the agreement with your team). With the i18next library, you can absolutely do that.</p><h3>Implementation of useTranslation hook</h3><p>Let&#39;s rebuild our Home component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f01a95dfbf8efa42a08b3f44d4c7577/href">https://medium.com/media/8f01a95dfbf8efa42a08b3f44d4c7577/href</a></iframe><p>In JSX, we call t method with key name as argument. Pretty straightforward.</p><h4>How to use it when a component is using multiple namespaces?</h4><p>useTranslation() accepts a string as a single namespace or array of namespaces. So when using multiple, you should write it like this:</p><pre>const { t } = useTranslation([&#39;&lt;namespace1&gt;&#39;, &#39;&lt;namespace2&gt;&#39;, &#39;&lt;namespace3&gt;&#39;])</pre><p>And in the t function, the namespace is separated by a colon:</p><pre>&lt;h2&gt;{t(&#39;&lt;namespace&gt;:&lt;key value&gt;&#39;)}&lt;/h2&gt;</pre><h3>Switching the language</h3><p>You probably want to choose a language, often placed somewhere in the navbar. In my case, I&#39;m choosing just between two languages, so a simple button is enough here. Of course, a dropdown could be also appropriate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/346e51b0ce433b79111b34c47d97e7f1/href">https://medium.com/media/346e51b0ce433b79111b34c47d97e7f1/href</a></iframe><p>Pretty straightforward, right?</p><p>Yeah, the code could be cleaned up. But what is important, is the logic of handleSwitchLanguage handler. The hook includes i18n.changeLanguage() , which accepts the abbreviation of the language.</p><p>I&#39;m storing the selected language in the currentLang state and changing it accordingly. With dropdown, it would be a pretty similar logic.</p><h3>What about testing?</h3><p>Of course, testing static text would make no sense if we use translation.</p><p>And by the way, we&#39;re using react-i18next instance in the whole app, so if you try to test component including translation, in React Testing Library you&#39;ll get this warning:</p><blockquote>react-i18next:: You will need to pass in an i18next instance by using initReactI18next</blockquote><p>So, can we mock the instance? Absolutely!</p><p>Let&#39;s have an exampleHome.test.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbc00187a760c91c16db4497db4829d0/href">https://medium.com/media/dbc00187a760c91c16db4497db4829d0/href</a></iframe><p>At the beginning of the file, you need to mock the react-i18next module before running any of the tests. In our example we mock t function of the useTranslation() hook, which is returning key passed as an argument.</p><p>But important thing is that we don&#39;t test text anymore. Instead, we&#39;re testing keys written in JSON files. If the namespace is stated within the code, you need to check it, too!</p><p>So it doesn&#39;t matter which language is active, it will always check for the right key value.</p><p>You can check, clone, or fork <a href="https://github.com/Dromediansk/countries-app-blog/tree/i18n">the final version of the GitHub repo</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62e1262c2c51" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/internationalization-i18n-in-react-using-hooks-62e1262c2c51">Internationalization (i18n) in React using hooks</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deno: Create Your First Web Application in Oak]]></title>
            <link>https://medium.com/better-programming/deno-create-your-first-web-application-in-oak-884868f8b30e?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/884868f8b30e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deno]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Wed, 07 Oct 2020 17:35:38 GMT</pubDate>
            <atom:updated>2020-10-07T17:35:38.757Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn about serving static files, routing, and error handling in Deno</h4><figure><img alt="Deno logo over a mountainscape." src="https://cdn-images-1.medium.com/max/1024/1*3t_PtZtkEvOSn290A1j4mg.png" /><figcaption>Photo by the author.</figcaption></figure><p>It looks like there is now silence after the hype. However, the <a href="https://deno.land/">Deno</a> community is still growing fast, so if you&#39;re interested in learning back end in Deno, it&#39;s the right time.</p><p>Deno came after Node.js, another runtime for JavaScript created by Ryan Dahl. It&#39;s built in Rust, supports TypeScript, and is secure by default.</p><p>Are you wondering why Dahl created another library? Check out the <a href="https://medium.com/better-programming/deno-vs-node-js-key-differences-8b2f4f63e2c7">key differences between Deno and Node.js</a>.</p><p>Anyway, in this article, you will learn how to set up and create a web application with <a href="https://github.com/oakserver/oak">Oak</a>, GitHub&#39;s most popular framework of Deno. Since Deno is server-side-oriented, we&#39;re going to create a web app with the ability to serve static files, provide API, and handle errors.</p><p>To follow and code along, you need to have Deno installed on your computer. Check out <a href="https://deno.land/#installation">the installation guide in the official docs</a> and follow the instructions.</p><p>Here&#39;s <a href="https://github.com/Dromediansk/deno-hello-world">the full version of the GitHub repo</a> we&#39;re going to build.</p><h3>Setting Up the Environment</h3><p>So firstly in your working directory, create new folders called src and public. In src, let&#39;s create a new file called mod.ts that will be our main file.</p><p>The reason why we use a TypeScript extension is that Deno supports TypeScript out of the box. It&#39;s also one of the main benefits over Node. Now to the coding part.</p><p>According to Oak’s documentation, we can create a very simple Hello World app by writing a few lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a5d7c1de8705808ca7c5c3c58bb0367/href">https://medium.com/media/6a5d7c1de8705808ca7c5c3c58bb0367/href</a></iframe><ul><li>We&#39;re importing Application from Oak by using a URL as a source. This is a standard implementation in Deno.</li><li>You can also use the particular version of the package by replacing Oak with oak@v.6.3.0. This way, you can make sure that all dependencies will be compatible and no breaking changes are included.</li><li>After importing, we create a reference of the Application.</li><li>Keep in mind that Oak&#39;s architecture is based on the middleware concept. But more about that later.</li><li>Now, when we&#39;re using app.use(), it expects ctx as the first parameter. ctx stands for context and you can read more about it in <a href="https://github.com/oakserver/oak">Oak’s documentation</a>.</li><li>Context can have different properties, such as ctx.response, in which we can send something (text or static files) in the response.</li><li>If the file is run as a program using the app.listen() method, we log text using log from Deno’s standard library and listen to the given address and port.</li><li>When navigating on your local machine to http://localhost:8000/, you should see the Hello world! message in your browser.</li></ul><p>Now, back to the core. What actually is a middleware?</p><h3>Explaining the Middleware Concept</h3><p>Middleware is just a special type of function that runs in the middle of the request coming into the API and response coming out of the API.</p><p>Of course, you can have multiple middlewares within your chain, but they should be executed in a predictable order. Each of them looks like this:</p><pre>app.use(async (ctx, next) =&gt; {})</pre><ul><li>Middleware always returns a Promise, so it&#39;s asynchronous.</li><li>As the first parameter, ctx is an object that includes request and response objects with appropriate properties and methods.</li><li>As the second parameter (optional), next() indicates to the application that it should continue executing other middleware in the chain.</li></ul><h3>Serving Static File</h3><p>Of course, showing only the &quot;Hello World&quot; text in our app is boring. We can also serve HTML.</p><p>Let&#39;s create one of your own or <a href="https://github.com/Dromediansk/deno-hello-world/blob/master/public/index.html">copy</a> it from a GitHub repo and save it in the public folder. Name it index.html.</p><p>For serving static files, we can create a middleware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1443d48722fc3b77a14f70650bc25495/href">https://medium.com/media/1443d48722fc3b77a14f70650bc25495/href</a></iframe><p>In the middleware, we’re improving the security with the principle of <a href="https://en.wikipedia.org/wiki/Whitelisting">listing of allowable entities</a> so that no one can use other malicious files. Deno will accept files only within the fileWhiteList array. Later, there should be also CSS, JavaScript files, favicon, etc.</p><p>If the file is present in the array, we&#39;re using the send() function from Oak that expects context, the file path to the file, and the object with the root property.</p><p>Now, that should work. Let&#39;s test it by running the deno run src/mod.ts command.</p><p>Whoops! After that, you&#39;ll see the following permission error in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94UJRnzwX7UMbTx0RGtfCw.png" /></figure><p>That&#39;s because Deno is keeping in mind the security factor. You need to give the app permission to network access with the --allow-net flag and to file system read access with the --allow-read flag:</p><pre>deno run --allow-net --allow-read src/mod.ts</pre><h3>Routing Using Router Middleware</h3><p>In every back-end app, we should apply endpoints for serving various data according to requests from the front end. Now, what if we want to keep our “Hello World” text on the main / route?</p><p>For that, we can use Router middleware.</p><p>Firstly, let&#39;s create a new file called api.ts in our src folder. As the name suggests, you can store all the API there:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd5494ee5b70024f1df05ecade977a0f/href">https://medium.com/media/fd5494ee5b70024f1df05ecade977a0f/href</a></iframe><p>In our route, we are using a GET method and returning a text as a response. Simple, right?</p><p>Now, back in our mod.ts file, we need to import our API and use the router middleware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1067c4b64525b7ad92c7d56d47a07be9/href">https://medium.com/media/1067c4b64525b7ad92c7d56d47a07be9/href</a></iframe><p>app.use(api.routes()) tells Deno to include all routes by our router (currently, we only have one). The next line tells Deno to allow all methods for this route(s), like GET, POST, PUT, and DELETE.</p><p>And now if you try to run the app (don&#39;t forget permissions), you should see the text on the / endpoint. But hold on. What if something has messed up with the server and we get an error? How do we handle such errors?</p><h3>Error Handling</h3><p>In Oak, it&#39;s pretty simple to implement. We need to:</p><ol><li>Add an event listener for handling errors.</li><li>Create a middleware for sending a response to the client if an error occurs.</li></ol><p>So in mod.ts, let&#39;s write the following code right at the beginning of the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/213294d9fc9254513855216ca38f714e/href">https://medium.com/media/213294d9fc9254513855216ca38f714e/href</a></iframe><p>In the middleware itself, await next() is saying to continue executing the other middleware in order if no error occurs. Otherwise, it will log an error message.</p><p>Of course, feel free to customize the handling based on the error code if you like.</p><h3>Summary</h3><p>It was pretty simple to build a web app, right?</p><p>With just a few minutes, you’ve built a simple web app that you can improve and develop on top of.</p><p>I really like the Oak framework because it has a moderate learning curve, it&#39;s easy to use, and secure by default. And although the Deno community is a bit small and no companies are using Deno so far, every technology needs time to establish itself on the market.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884868f8b30e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/deno-create-your-first-web-application-in-oak-884868f8b30e">Deno: Create Your First Web Application in Oak</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[Deno vs. Node.js — Key Differences]]></title>
            <link>https://medium.com/better-programming/deno-vs-node-js-key-differences-8b2f4f63e2c7?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b2f4f63e2c7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deno]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 03:22:09 GMT</pubDate>
            <atom:updated>2020-07-28T03:55:55.283Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deno vs. Node.js — Key Differences</h3><h4>The new JavaScript library everyone is talking about, from the creator of Node</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdUYc-UwlO4d107aEBN6-A.jpeg" /><figcaption>Image source: Author</figcaption></figure><p><em>Should I learn Deno? What&#39;s the main benefit of using Deno over Node?</em></p><p>After reading this story you&#39;ll know key principles of how <a href="https://deno.land/">Deno</a> works, who is behind it, and why there are so many discussions about it. I&#39;ll compare it with Node.js as it is the most popular runtime for JavaScript so far.</p><p><a href="https://nodejs.org/en/">Node</a> has the same creator as Deno, Ryan Dahl. The right question is then, “why has he created another library if Node is already settled in the market and favored by many companies?”</p><h3>The Support Behind the Scene</h3><p><a href="https://deno.land/">Official docs</a> say:</p><blockquote>“Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 engine and is built in Rust.”</blockquote><p>That is also the main reason why Deno could be very successful. There are big companies behind it:</p><ul><li>Rust created by Mozilla</li><li>TypeScript from Microsoft</li><li>V8 engine from Google</li></ul><p>On the other hand, Node is built in C and C++, which tend to be less secure compared to Rust. It doesn&#39;t have TypeScript compiler built in, so in order to use it, you need to install it with npm.</p><p>What they have common is the V8 engine from Google under the hood — the same one that drives the Chrome browser.</p><h3>ES Modules vs. CommonJS</h3><p>In 2009, when Node was created, JavaScript didn&#39;t have its own module system. Hence, by default, CommonJS syntax is used in Node:</p><pre>const bcrypt = require(&#39;bcrypt&#39;);</pre><p>The problem is that this isn&#39;t really JavaScript<em>.</em> It&#39;s a non-standard way of including different pieces of code from third-party libraries.</p><p>Fortunately, in 2015 ES6, introduced its own module system for JavaScript, so now you can do this:</p><pre>import bcrypt from &#39;bcrypt&#39;</pre><p>Compared to Deno, ES modules are used in Deno out of the box. That means you can actually import URLs without installing it through npm:</p><pre>import &#39;<a href="https://deno.land/std/examples/chat/server.ts">https://deno.land/std/examples/chat/server.ts</a>&#39;</pre><p>With that ability, you can import basically any piece of program and use it in your code. However, if you do it just like that, you will get a permission error.</p><p>The reason is that Deno is also keeping security in mind.</p><h3>Security First</h3><p>Although Node is becoming more and more popular, many companies are tending to bypass it. One of the most important reasons is that it has flaws in security.</p><p>The issue is that Node is using npm in order to install external modules for the app. And because npm is opened to the community and everyone can create one, one can potentially inject malicious things.</p><p>And Node will trust this module without any complaints.</p><p>On the other hand, Deno is using the <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">principle of least privilege</a> and the <a href="https://en.wikipedia.org/wiki/Whitelisting">listing of allowable entities</a>. You can grant permissions to each module individually. That itself solves many potential security issues when developing the server.</p><h3>Built-In Tools</h3><p>To start to develop an app with Node, you have to decide what tools will be used in the first place.</p><p>Are you going to use TypeScript? Then install <a href="https://github.com/TypeStrong/ts-node">ts-node</a>. What about testing? Let&#39;s use <a href="https://jestjs.io/">Jest</a>. What about formatting? Bundling? etc.</p><p>With Deno, you don&#39;t have to solve these problems because it comes with these tools preinstalled. And since it&#39;s standardized for Deno, you can be sure that these tools have full support. Really cool.</p><h3>Browser-Compatible API</h3><p>I consider this as one of the biggest differences between Node and Deno.</p><p>As you already might know, browsers have window as a global object, which has many properties and methods such as addEventListener, setTimeout, setInterval, etc.</p><p>Browsers also use fetch to send a request to the given URL and return Promise.</p><p>In Deno, you have all these things built-in. This is perfect, especially for front-end developers, who are using these methods daily.</p><h4>What about Node?</h4><p>In Node, fetch doesn&#39;t exist. If you want to use it, you need to install something like <a href="https://www.npmjs.com/package/node-fetch">node-fetch</a> or <a href="https://github.com/npm/node-fetch-npm">node-fetch-npm</a>. <em>But which one is the right one? Will this work in my project?</em></p><p>Node also use global as the main object, which is not part of the browser. So it&#39;s not really JavaScript.</p><h3>Single Executable</h3><p>When using Deno, you always have a single executable file, e.g. deno.exe, which you can double-click and run Deno runtime. So basically you can write programs using JavaScript and then share with other computers with ease.</p><p>In Node, there&#39;s no such option as a single executable, because the app needs to run with all necessary packages under the node-modules folder.</p><h3>Async Returns Promises</h3><p>Asynchronous code in Deno always returns Promise. In Node, that&#39;s not always the case.</p><p>Node was created before we had Promise-based syntax. Although in many cases asynchronous code returns Promise, sometimes you have to do workarounds with constructors like <a href="https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original">util.promisify</a>.</p><p>In fact, anytime a new feature is introduced in JavaScript, Node needs to do some workarounds in order to have them compatible. In contrast, Deno supports the newest JavaScript features out of the box.</p><p>Its back end is written in Rust, which handles asynchronous code with something called <em>futures</em>. Under the hood, it translates asynchronous code into Promises.</p><p>This means that in Deno you can use async await without any issues.</p><h3>To Sum Things Up</h3><p><em>So, should I immediately start using Deno?</em></p><p>I would say, “Not really.”</p><p>I mean, sure, it looks very promising when looking at all the features and how it&#39;s built. It basically solves a lot of issues that Node has in its core.</p><p>Deno is supported by big companies, it uses the newest JavaScript, and its security is on a high level. But every technology has its flaws, of course.</p><p>And so far, the biggest flaw of Deno is that it&#39;s only in the early stage. The community is just starting to grow. So only time will show us whether it will catch up with languages such as Node, Java, or PHP — or whether it&#39;s just initial hype.</p><p>If you enjoyed reading, you might be interested in some of my other stories:</p><ul><li><a href="https://levelup.gitconnected.com/what-you-should-know-about-npm-2b198dab6e9d">What You Should Know About NPM</a></li><li><a href="https://levelup.gitconnected.com/learn-gatsby-by-building-your-own-blog-website-ff5aaa8e90b8">Learn Gatsby by Building Your Own Blog Website</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b2f4f63e2c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/deno-vs-node-js-key-differences-8b2f4f63e2c7">Deno vs. Node.js — Key Differences</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[Testing a Custom React Hook]]></title>
            <link>https://levelup.gitconnected.com/testing-a-custom-react-hook-21ae732228b7?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/21ae732228b7</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 15:10:14 GMT</pubDate>
            <atom:updated>2020-06-19T15:10:14.038Z</atom:updated>
            <content:encoded><![CDATA[<h4>And gaining more confidence in your React Testing Library skills</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mh5l55_i_nc41FxU" /><figcaption>Photo by <a href="https://unsplash.com/@battlecreekcoffeeroasters?utm_source=medium&amp;utm_medium=referral">Battlecreek Coffee Roasters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I wrote a story about <a href="https://medium.com/better-programming/how-to-build-a-custom-react-hook-for-fetching-data-cf942e64e9f8">How to Build a Custom React Hook for Fetching Data</a>. The implementation of the useFetch is pretty straightforward, but it&#39;s a bit tricky to test properly.</p><p>We&#39;re going to use React Testing Library (RTL) with the assumption that you already have set up your testing environment.</p><p>Ok, let&#39;s just not talk in vain and jump straight to the code!</p><h3>Creating the useFetch</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/229c2f34771bfa57ab21facc5ed806cb/href">https://medium.com/media/229c2f34771bfa57ab21facc5ed806cb/href</a></iframe><p>A custom hook is a special type of function, in which you can use React hooks.</p><p>So here we&#39;re fetching data from the API in the useEffect hook, putting them into state and returning. If an error occurs during fetch, we return the error.</p><p>But before anything else, with ref.current we&#39;re checking if the current reference to the component is true. If it&#39;s not, it means the component is not mounted to the view. Therefore fetching data should not happen.</p><h3>Testing custom hook</h3><p>Now, we can cover the whole functionality of the useFetch by testing whether:</p><ol><li>data are returned after a successful asynchronous call to the API</li><li>an error is handled correctly when occurs</li><li>call to the API is not happening when the current reference is falsy</li></ol><p>For each point, we can write a separate test, right? So let&#39;s get started!</p><h4>Setting up a testing file</h4><p>Suppose we create a new file useFetch.test.js and prepare a testing environment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68301b41e3dcf5377c396dbb8580b368/href">https://medium.com/media/68301b41e3dcf5377c396dbb8580b368/href</a></iframe><ul><li>We will definitely need mocked data since we&#39;re not going to really fetch them. Hence I created an array of stubbedCountries.</li><li>In afterEach block we clean up fetch implementations, whereas in afterAll we restore the original implementation. This way we prevent tests to affect each other. More about this in <a href="https://jestjs.io/docs/en/mock-function-api.html#mockfnmockclear">jest doc</a>s.</li></ul><h4>Case 1: Getting the data</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdd7263ee3be88bf931223a20ed3698d/href">https://medium.com/media/bdd7263ee3be88bf931223a20ed3698d/href</a></iframe><p>Ok, now let&#39;s talk about this step by step:</p><ul><li>As always, we firstly mock asynchronous call by returning resolved Promise with stubbedCountries.</li><li>Hooks are special types of functions because they can be used only within React components. Hence we need somehow to mock rendering hook in the component. For that, we can use renderHook().</li><li>A callback of renderHook() is an execution of the hook with proper arguments. You can read about <a href="https://react-hooks-testing-library.com/reference/api#renderhook">more options of </a><a href="https://react-hooks-testing-library.com/reference/api#renderhook">renderHook()</a>.</li><li>After that, we call waitForNextUpdate() which returns a Promise that resolves the next time the hook renders, commonly when a state is updated as the result of an asynchronous update.</li><li>We expect the result (returned object) should strictly equal to the desired output.</li></ul><h4>Case 2: Error handling</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c66826a04132c7ee975e7cc3280923c/href">https://medium.com/media/2c66826a04132c7ee975e7cc3280923c/href</a></iframe><p>This is pretty similar to the previous test:</p><ul><li>Again, we mock asynchronous call by returning Promise which must be with rejected status. It means something went wrong and the error should be caught.</li><li>Same as above, we render our hook and call waitForNextUpdate().</li><li>We expect the returned object should contain error and no data.</li></ul><h4>Case 3: Current reference is falsy</h4><p>The React component which uses the useFetch was in the meantime unmounted from the DOM and therefore fetching should not be triggered:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b21c79eea2f26cdcf1f9d4afd625de72/href">https://medium.com/media/b21c79eea2f26cdcf1f9d4afd625de72/href</a></iframe><ul><li>Here we&#39;re just rendering the hook with given arguments. The second argument is ref, so it must be { current: false }.</li><li>In assertion, we expect that fetch has not been called. This means useEffect in the custom hook has not been called.</li><li>We also expect the returned object should not include data nor error.</li></ul><h3>Conclusion</h3><p>In the end, this is what we were trying to achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-RmM2aBYyMUyixSJp1lRg.png" /></figure><p>You can also check the <a href="https://github.com/Dromediansk/countries-app-blog/blob/custom-hook-unit-testing/src/utils/customHook.test.js">test file in the GitHub repo</a>.</p><p>However, what&#39;s important that we covered all possible cases with just 3 tests. This means, that coverage should be 100%, although I don&#39;t consider this aspect as relevant.</p><p>And the best thing is, that you can use this hook in every React project because the code is fully tested!</p><p>Want to learn more about testing? Feel free to read my other stories:</p><h4>Unit testing with RTL</h4><p><a href="https://levelup.gitconnected.com/how-to-write-unit-tests-with-react-testing-library-d9624fd2b707">How To Write Unit Tests with React-Testing-Library</a></p><h4>Automation (E2E) testing with Cypress</h4><p><a href="https://medium.com/better-programming/react-testing-get-started-with-cypress-io-a19b6eb6332a">React Testing: Get Started With Cypress.io</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21ae732228b7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/testing-a-custom-react-hook-21ae732228b7">Testing a Custom React Hook</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Write Unit Tests with React-Testing-Library]]></title>
            <link>https://levelup.gitconnected.com/how-to-write-unit-tests-with-react-testing-library-d9624fd2b707?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9624fd2b707</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Fri, 12 Jun 2020 12:46:46 GMT</pubDate>
            <atom:updated>2020-06-12T12:46:46.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Simple isolated tests with testing-library/react v10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CJiehYwYKQnll9ZC" /><figcaption>Photo by <a href="https://unsplash.com/@cdc?utm_source=medium&amp;utm_medium=referral">CDC</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So you&#39;ve developed a React application, but you&#39;re still not 100% confident about its functionality and predictability.</p><p>Or you implemented a gorgeous function, but then bugs have started to appear. You have no idea what could be a reason. Pretty frustrating, right?</p><p>Those two cases are reasons why unit tests are important.</p><h3>Setting up our application</h3><p>I want to demonstrate unit testing on the Countries app, which you can <a href="https://github.com/Dromediansk/countries-app-blog/tree/testing">clone from GitHub</a> and code along.</p><p>In order to have the same results, I recommend you using the following dependency versions (or newer):</p><ul><li>react — 16.13.1</li><li>react-scripts — 3.4.1</li></ul><p>Or if you want to develop the app completely from scratch, you can start by reading the following piece:</p><p><a href="https://medium.com/better-programming/some-best-practices-for-building-a-react-app-with-hooks-d6157494f5c1">Some Best Practices for Building a React App With Hooks</a></p><h4>Installing RTL</h4><p>To get started, first we need to install React-testing-library (RTL) and jest-dom for using <a href="https://github.com/testing-library/jest-dom">custom jest matchers</a>:</p><pre>npm install --save-dev @testing-library/react @testing-library/jest-dom</pre><p>To actually able to use custom matchers, we need to import them. In src folder, let&#39;s create a new file setupTests.js:</p><pre>import &quot;@testing-library/jest-dom/extend-expect&quot;;</pre><p>Each setup file will be run once per test file. You can read more about that in <a href="https://jestjs.io/docs/en/configuration.html#setupfiles-array">jest documentation</a>.</p><h3>Snapshot testing</h3><p>Snapshot tests are very useful whenever you want to make sure your UI or code does not change unexpectedly.</p><p>How snapshot testing works is that it compares the component with the generated blueprint (snapshot). If they don&#39;t match, the test will fail.</p><p>For instance, let&#39;s have a simple component CountryCard.js without any logic inside:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df054a70e3bf891d8fbea76da29ec0c2/href">https://medium.com/media/df054a70e3bf891d8fbea76da29ec0c2/href</a></iframe><p>In CountryCard folder let&#39;s create a new file CountryCard.test.js and write our very first test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa9ec31db2295bc3cc0043ab547cf369/href">https://medium.com/media/aa9ec31db2295bc3cc0043ab547cf369/href</a></iframe><ul><li>before running any test, we need to define a country object with required properties, in our case stubbedCountry. The values of the properties should have the same prop type as expected.</li><li>on line 15 we&#39;re rendering our component with render() and passing the stubbed props to the component.</li><li>we expect to match snapshot (which will be generated if running the first time).</li></ul><h4>What&#39;s the real benefit?</h4><p>Based on that example, it looks like snapshot tests are not very useful, right? We&#39;re mocking props, passing to the component, and then expect it will always match. Why they shouldn&#39;t, anyway?</p><p>The thing is, CountryCard is expecting to have only one prop and it will show the content. There&#39;s no other possible version of the component.</p><p>Therefore, snapshot tests have a purpose only when:</p><ul><li>the content of the component is changing due to different props. In that case, we can write a snapshot test for all possible versions of the component.</li><li>we want to recognize changes in the component during development.</li></ul><h3>Testing forms</h3><p>Forms are one of the most important topics when developing a web app and it&#39;s crucial to have them predictable.</p><p>AdvancedFilter.js consists of basic inputs, which values are passed from the upper component. Also, an event handler is passed to the component as prop — handleChangeValue.</p><p>So what should we actually test here?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b0e0488bc5496c6562c82462ba251c8/href">https://medium.com/media/9b0e0488bc5496c6562c82462ba251c8/href</a></iframe><p>As mentioned above, unit tests should be as much isolated as possible. What’s important is to test the behavior of the component and have expected results.</p><p>Here&#39;s what we want to test:</p><ol><li>Based on given props, it should show corresponding input values</li><li>When a user starts typing in the input, it should call an event handler and show the updated value</li></ol><p>This is eligible to check in two tests! Let&#39;s test the first case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/099b9ae9e5caf4a3f00c26769c791fea/href">https://medium.com/media/099b9ae9e5caf4a3f00c26769c791fea/href</a></iframe><ul><li>We can group multiple tests in describe block (starting on line 5).</li><li>It&#39;s good practice to create mocked functions and props at the beginning of tests. In our case, we need to mock the required props searchValue and handleChangeValue.</li><li>In the test, we first need to render our tested component with proper props. In RTL we use render() function.</li><li>Using object destructuring, we can extract methods we will use — such as selector method getByTestId.</li><li>In the end, we (initially) expect that input values are empty strings. In expect we need to pass some selector, e.g. by text, label text, test-id, etc. You can read about all available options in <a href="https://testing-library.com/docs/dom-testing-library/api-queries">queries of RTL</a>.</li></ul><h4>Simulating events</h4><p>Of course, testing initial values in forms is not enough. We can simulate user behavior using fireEvent from RTL:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb28c9f23780d64d9c16345cbd100807/href">https://medium.com/media/eb28c9f23780d64d9c16345cbd100807/href</a></iframe><p>There are several things happening in this test:</p><ul><li>We firstly define newly updated searchValue prop, which will be passed to the component when the user writes something in the input (line 5).</li><li>We render the component with initial values.</li><li>onChange event can be simulated with fireEvent.change according to the <a href="https://testing-library.com/docs/dom-testing-library/api-events">RTL documentation</a>. Don&#39;t forget to wrap it into act() block as we&#39;re performing updates to the component.</li><li>After changing the value of the input, we need to simulate r<a href="https://testing-library.com/docs/marko-testing-library/api#rerender">e-rendering the same component with different props</a> (line 19).</li><li>In assertion, we&#39;re checking the value of the input as well as event handler has been called.</li></ul><p><strong>Note: </strong>Keep in mind that we were not testing the event handler itself. This must be done in the component, where it&#39;s defined — in our case in CountriesContainer.js.</p><h3>Testing fetch service</h3><p>In our app, we&#39;re using a custom hook for fetching countries, but in the usual scenario, you would have some calling service for that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09a006ee3bff2e827c233ede9b8c29af/href">https://medium.com/media/09a006ee3bff2e827c233ede9b8c29af/href</a></iframe><p>Fetching data is usually mocked and we should test just behavior of our service in isolation.</p><h4>1. Scenario with status code 200</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a344bfa31f92951adfdf0030db729a80/href">https://medium.com/media/a344bfa31f92951adfdf0030db729a80/href</a></iframe><ul><li>What&#39;s important is to mock fetch at the beginning, where we return a Promise with given status and data (lines 17–25).</li><li>Assert results.</li></ul><h4>2. Scenario with status code 500</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d982390c257505ac46f54f1771163f24/href">https://medium.com/media/d982390c257505ac46f54f1771163f24/href</a></iframe><ul><li>Similar to the previous test, we need to mock fetch with status 500.</li><li>We expect data are not present</li></ul><h3>Testing fetched data</h3><p>The true magic happens in the CountriesContainer, in which we&#39;re fetching data, declaring event handler of the form, and showing countries. I&#39;d consider this component as most crucial to test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50d2341535b10c8a770ecdb301750b11/href">https://medium.com/media/50d2341535b10c8a770ecdb301750b11/href</a></iframe><p>Here&#39;s what we actually need to check:</p><ol><li>Is loading spinner shown when data are being fetched?</li><li>Are data shown in the view after fetch?</li><li>Is error notification displayed if data are not successfully fetched?</li><li>Are countries filtered by input value?</li></ol><h4>Test preparation</h4><p>Firstly, we actually need to mock the custom hook for getting the data and data itself. In CountriesContainer.test.js we can do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1e3c66f85c4e2fbc5cb1bb44e5dbbf9/href">https://medium.com/media/e1e3c66f85c4e2fbc5cb1bb44e5dbbf9/href</a></iframe><ul><li>We can mock any module using <a href="https://jestjs.io/docs/en/manual-mocks">Jest manual mocks</a> (line 6).</li><li>stubbedCountries are data that will be shown after (simulated) fetch.</li></ul><p>Now, let&#39;s dive into writing tests itself!</p><h4>1. Checking loading spinner</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93c6ec2fc4de9c180bc524261a78c128/href">https://medium.com/media/93c6ec2fc4de9c180bc524261a78c128/href</a></iframe><p>What&#39;s interesting here is that we first need to mock data fetching. Since we&#39;re using the custom hook for that purpose, we have to mock the returned value of the function (lines 2–6).</p><p>In case you&#39;re directly using Axios or fetchAPI, you need to mock those modules. Check <a href="https://testing-library.com/docs/dom-testing-library/api-async">Async utilities in RTL</a>.</p><p>After that, we can render the component and expect that the loading spinner is being shown.</p><h4>2. Check data are being shown</h4><p>This is actually pretty simple. We mock the returned value of the hook, in which data are already present.</p><p>We can query tags, which are inside child components. Sometimes it&#39;s inevitable. For example, the selection of the country card is by data-testid:</p><pre>// CountryCard.js</pre><pre>&lt;div className=&quot;country-card&quot; <strong>data-testid={`${country.name}-card`}</strong>&gt;<br>...</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8244cc0da029e8fb31be625f610e525/href">https://medium.com/media/b8244cc0da029e8fb31be625f610e525/href</a></iframe><h4>3. Check error notification</h4><p>Here we just change the returned value of the hook and check if the error message is there:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40d5af780e5c1ff3e9684de4bc98a902/href">https://medium.com/media/40d5af780e5c1ff3e9684de4bc98a902/href</a></iframe><h4>4. Check filtering countries</h4><p>After data are being fetched, we need to simulate onChange event on the inputs. I&#39;ll demonstrate how to filter by country name, but feel free to add more tests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a92e70205afcdf9d15e67214e8a085fa/href">https://medium.com/media/a92e70205afcdf9d15e67214e8a085fa/href</a></iframe><p>We&#39;re simulating typing &#39;Slov&#39; into name input and expect, that only Slovakia country will be visible in the view. With this test, we&#39;re also covering the event handler declared in the component.</p><h3>Where to go next</h3><p>You can check all tests in the <a href="https://github.com/Dromediansk/countries-app-blog/tree/unit-testing">GitHub repo</a>.</p><p>With these several test examples, we covered pretty much the core of the unit testing. I encourage you to write even more tests. It&#39;s a topic in which you need practice, so you can decide <em>what</em> to actually test.</p><p>If you&#39;re interested in learning automation/E2E testing, I wrote a guide about how to write tests in Cypress:</p><p><a href="https://medium.com/better-programming/react-testing-get-started-with-cypress-io-a19b6eb6332a">React Testing: Get Started With Cypress.io</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9624fd2b707" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-write-unit-tests-with-react-testing-library-d9624fd2b707">How To Write Unit Tests with React-Testing-Library</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What You Should Know About NPM]]></title>
            <link>https://levelup.gitconnected.com/what-you-should-know-about-npm-2b198dab6e9d?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b198dab6e9d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Tue, 05 May 2020 12:57:59 GMT</pubDate>
            <atom:updated>2020-05-05T12:57:59.931Z</atom:updated>
            <content:encoded><![CDATA[<p>Commands and core principles you should master.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uMNlX4gEbbnk0w0h" /><figcaption>Photo by <a href="https://unsplash.com/@pinjasaur?utm_source=medium&amp;utm_medium=referral">Paul Esch-Laurent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>NPM or Node Package Manager is a cornerstone for today’s web development. Whether you work with Node.js or you’re building a front-end with a library like React or Angular, this skill is inevitable.</p><p>I can’t imagine developing an app without using NPM (but I’m pretty sure there’s a way). It allows you to manage packages and provides a useful interface to work with them.</p><h3>Installation of NPM</h3><p>If you want to initialize NPM for your project, it’s required to have installed Node.js on your computer. This includes everything you need for the start.</p><p>You can download Node from<a href="https://nodejs.org/"> the official page</a>. Just follow the instructions and you’re good to go.</p><p>Now to make sure that NPM is present on your computer, you can open the terminal and type following command:</p><pre>npm -v</pre><p>It should show the current version of the installed package, e.g. 6.13.4.</p><h3>npm init</h3><p>In order to install, update, or remove packages in your project, you must have package.json initialized. Most of the starting packages such as Create React App already have this file. In this case, you can skip this step.</p><p>Otherwise, you can initialize npm with the following command:</p><pre>npm init -y</pre><p><strong>Note:</strong> if you want to generate package.json faster, you can add -y flag to the command.</p><h3>Dismantling package.json</h3><p>Now, to have a good understanding of how NPM works and how to handle the configuration of the project correctly, you should know what package.json includes.</p><p>Let&#39;s have an example from Create React App package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68f6e5c6867b405a9dc26ad9a63c53a3/href">https://medium.com/media/68f6e5c6867b405a9dc26ad9a63c53a3/href</a></iframe><ul><li>You can see all the installed packages in the dependencies and devDependencies. What is the difference?</li><li>dependencies should contain libraries and frameworks your app is built on, such as Vue, React, Angular, Express, etc. These packages are obviously used in production as well as during development.</li><li>devDependencies should contain packages used during development or which are used to build your bundle, for example, testing libraries, jest, gulp-jade, etc. These packages are necessary only while you are developing your project.</li><li>You can define your own commands in thescripts. For example, by running npm start you will run React app locally or by running npm test all written unit tests.</li></ul><p><strong>Note:</strong> Be careful to run npm eject, because this is a one-way operation!</p><p>npm eject will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc.) into your project as dependencies in package.json. This can be useful if you want to configure bundling and building the project by yourself.</p><h3>Versioning of dependencies</h3><p>Every package in package.json is written in key-value pair. The key is for the name of the package and value is the version.</p><p>The version number is in S<a href="http://semver.org/">emVer syntax</a> (Semantic Versioning Specification) which designates each section with a different meaning. SemVer is broken into three sections separated by a dot:</p><pre>&quot;react-scripts&quot;: &quot;3.3.0&quot;</pre><pre>// &quot;react-scripts&quot;: major.minor.patch</pre><p>Major, minor, and patch represent the different releases of a package:</p><ul><li><em>major</em> — if the major version is released, it includes breaking changes to dependency, which can cause unexpected behavior of the app.</li><li><em>minor</em> — includes backward compatible new features. The operation of the app should not be affected.</li><li><em>patch</em> — includes backward compatible bug fixes.</li></ul><h4>What about ~ and ^?</h4><p>npm uses the tilde (~) and caret (^) to designate which patch and minor versions to use respectively.</p><p>So if you see ~1.0.2 it means to install version 1.0.2 or the latest patch version such as 1.0.4. If you see ^1.0.2 it means to install version 1.0.2 or the latest minor or patch version such as 1.1.0.</p><h3>npm install</h3><p>Now, since you know what package.json includes, you probably would like to install other dependencies to your project. You can do that like this:</p><pre>npm i lodash --save</pre><p>i stands for install and lodash is the name of the package. You should also add flag --save to save it into dependencies.</p><p>If you want to install a package as devDependency, you should add flag --save-dev or just -D.</p><p>To install dependency globally on your machine, add -g flag and you are good to go.</p><p><strong>Note:</strong> You should always read the documentation of the package whether it should be installed into dependencies or devDependencies.</p><h3>npm update</h3><p>The common problem of NPM dependencies is that new versions are released often and they should stay up-to-date for various security and vulnerability reasons. So what is the appropriate strategy for updating?</p><p>Well, firstly let&#39;s explore which dependencies should be updated:</p><pre>npm outdated</pre><p>You will get a table similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnrVyQOoe5kGCzpHEZPmQw.png" /></figure><p>This table shows that packages should be updated to the version given in the &quot;Wanted&quot; column. You can fix it by the following command:</p><pre>npm update</pre><pre>// or</pre><pre>npm update &lt;dependency_name&gt;</pre><p>However, if dependency requires a major update, it won&#39;t work with this command because it includes breaking changes.</p><p>These cases should be updated manually by rewriting version in package.json and running npm install. After that, you should review your code and test the app.</p><h3>npm audit</h3><p>It can be pretty annoying if you install your desired packages and on the last line you see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*B11eiq8XmSAnyXBUmFHhqQ.png" /></figure><p>To view more details you can run the command npm audit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oc5bve9Ccvdgu6O1nQH9LQ.png" /></figure><p>You’ll get a detailed list of packages that have vulnerabilities. If you look at the Path field, it shows the dependency path. So, in this case, <em>react-scripts</em> depends on <em>jest</em>, which depends on <em>jest-cli</em>, etc. In the end, the <em>kind-of</em> dependency contains a vulnerability that should be fixed.</p><p>Many vulnerabilities can be fixed by running updating dependencies mentioned above or this:</p><pre>npm audit fix</pre><p>However, some dependencies might not be fixed automatically. This happens if you’re using a package that’s undergone a major change that could break your current project if updated. In this case, you should review your code manually.</p><h3>Final words</h3><p>With every new release, NPM is making huge strides into the world of front-end development. <a href="https://frontendhappyhour.com/episodes/npm-install-beer-save-in-mouth/">According to its co-founder Laurie Voss</a>, its user base is changing and most of those using it are not using it to write Node at all.</p><p>Rather, it’s becoming a tool that people use to put JavaScript together on the front end and one which is becoming an integral part of writing modern JavaScript.</p><p>However, its downside is regular dependency updates which can cause a lot of pain when maintaining projects. Therefore it&#39;s good practice to have defined strategy for development and maintenance in parallel.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b198dab6e9d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/what-you-should-know-about-npm-2b198dab6e9d">What You Should Know About NPM</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Custom React Hook for Fetching Data]]></title>
            <link>https://medium.com/better-programming/how-to-build-a-custom-react-hook-for-fetching-data-cf942e64e9f8?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf942e64e9f8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Thu, 09 Apr 2020 16:11:09 GMT</pubDate>
            <atom:updated>2020-06-21T06:23:10.066Z</atom:updated>
            <content:encoded><![CDATA[<h4>An elegant and reusable solution, suitable for using fetchAPI and Axios</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abhwJ5CWMAJjopV-woRW9Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@twixes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Twixes</a> on <a href="https://unsplash.com/s/photos/future?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’m sure you’ve heard the hype around React Hooks. There’s no need to give you the basics — the internet is full of this. Also, if you’re interested in building custom Hooks, you probably already know a bit about them.</p><p>So let’s get right to the code.</p><h3>Sample Code for Getting Data</h3><p>Most web apps use some sort of API for getting data. First, we’re going to create a sample code.</p><p>Let’s use the component UserList.js, where we want to fetch users after the page is mounted to the view. For demonstration purposes, I’ll use the fake API <a href="https://jsonplaceholder.typicode.com/">JSONplaceholder</a>.</p><p>The component’s basics will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da76554a287c897330cc443c0066774f/href">https://medium.com/media/da76554a287c897330cc443c0066774f/href</a></iframe><p>We’re going to save data in state users which is handled by useState Hook. During fetching, we’ll show a loading message to give a better user experience.</p><h3>Data Fetching</h3><p>In React 16.8 and higher, this is done with the useEffect Hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e81223d555e580cf555bbd53a4d65d10/href">https://medium.com/media/e81223d555e580cf555bbd53a4d65d10/href</a></iframe><ul><li>First, we set loading to true.</li><li>The whole code block for getting the data is called as soon as it’s defined (lines 6 and 18). This quirk is called an “<a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">Immediately Invoked Function Expression</a>” (or IIFE).</li><li>I’m using async-await instead of a traditional Promise based approach. For proper handling of errors, I’ve implemented try-catch-finally<em> </em>blocks.</li><li>In this case, Fetch API is used, but you can use <a href="https://github.com/axios/axios">Axios</a> as well.</li></ul><h3>Performance Optimization</h3><p>You should always keep the performance aspects of your code in mind.</p><p>To prevent from fetching data on unmounted component, we can use another Hook, useRef. The purpose is that it should run code within useEffect only if the component is mounted to the view. Otherwise, you might get this familiar (to React developers) warning:</p><blockquote>Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.</blockquote><p>Here’s the final version of useEffect:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bd681f7a1301fcc1c6960507125fce4/href">https://medium.com/media/8bd681f7a1301fcc1c6960507125fce4/href</a></iframe><p>On line four we first check whether the component is mounted. If yes, we try to fetch the data. It’s also important to set the current reference to false in the cleanup function (lines 26–28).</p><h3>Creating a Reusable Custom Hook</h3><p>Our useEffect has grown into a lot of codes, which could pollute the component’s environment. If you fetch data in several components inside the project, you’re also breaking the DRY (Don’t Repeat Yourself) principle .</p><h4>Implementing built-in hooks from React</h4><p>Let’s create a new file useFetch.js with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cdbfdb92ab56ce1383a43a2de3841bb/href">https://medium.com/media/1cdbfdb92ab56ce1383a43a2de3841bb/href</a></iframe><ul><li>useFetch is just a special type of function, which will include built-in hooks from React.</li><li>It accepts parameters — URL, reference and initial value for the state.</li><li>This hook will store data, error, and loading in states accordingly (lines 4–6).</li></ul><p>Now the only thing we’re still missing is data fetching itself. We can do that in useEffect, as above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/229c2f34771bfa57ab21facc5ed806cb/href">https://medium.com/media/229c2f34771bfa57ab21facc5ed806cb/href</a></iframe><p>This custom Hook must return states we defined. We can do it by using object destructuring on line 26.</p><h4>Back to our component</h4><p>Now we’re ready to use the custom Hook inside the component. Remove unnecessary code and store results of the Hook in variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dd668550c8947ba21279d838cf19625/href">https://medium.com/media/0dd668550c8947ba21279d838cf19625/href</a></iframe><p>In useFetch(), we’re passing URL for fetching users, isComponentMounted as a reference, and empty array as the initial value for data.</p><p>Now our users will be stored in data and the component will re-render as soon as data is fetched or an error occurs. You can handle errors within the component according to your needs.</p><h3>How to test it?</h3><p>So you just created a reusable custom Hook, which you can use across all React projects. But is it really reliable?</p><p>To find it out, you should write some unit tests. Feel free to continue reading my next article about this topic:</p><p><a href="https://levelup.gitconnected.com/testing-a-custom-react-hook-21ae732228b7">Testing a Custom React Hook</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf942e64e9f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-build-a-custom-react-hook-for-fetching-data-cf942e64e9f8">How to Build a Custom React Hook for Fetching Data</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 Comprehensive Guide to Flexbox]]></title>
            <link>https://medium.com/better-programming/a-comprehensive-guide-to-flexbox-ca0ffdf770c6?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca0ffdf770c6</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Tue, 07 Apr 2020 13:38:49 GMT</pubDate>
            <atom:updated>2020-04-08T17:15:49.206Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn Flexbox with some humor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c3sH0A4bCoIwJjPA" /><figcaption>Photo by <a href="https://unsplash.com/@halgatewood?utm_source=medium&amp;utm_medium=referral">Hal Gatewood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a good frontend developer, you can’t overlook Flexbox in 2020. It’s a CSS module that helps you make your website responsive with ease.</p><p>However, the application of Flexbox can be quite confusing if you don’t grasp the main principles.</p><p>I’ll introduce you to all off its important quirks and properties. There will also be three challenges, in which I’ll demonstrate the proper usage of individual properties. Feel free to try them on your own in this <a href="https://codepen.io/Dromedian_sk/pen/RwPyewQ?editors=1100">code snippet in CodePen</a>.</p><p>Also, a big thank you to <a href="https://medium.com/u/b224eb94799d">Bernar May</a> for providing apt pictures of every Flexbox property!</p><h3><strong>Inevitable Basics</strong></h3><p>Flexbox involves its own set of properties you can use. It’s important to learn the main principles of how it works.</p><p>For starting out, let’s take a look at this figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*Ou1rhSpubrFjDIqboGGVqg.png" /><figcaption>Basic figure of Flexbox principles</figcaption></figure><p>When applying a Flexbox to your app, there’s always a <em>flex container</em>, which is the parent element of the <em>flex items.</em></p><p>You should also distinguish between the <em>main axis</em> and <em>cross axis. </em>The main axis of a flex container is the primary axis along which flex items are laid out. The axis perpendicular to the main axis is called the cross axis. Its direction depends on the main axis direction.</p><p><strong>Note:</strong> The main axis is not necessarily horizontal; it depends on the flex-direction property (see below).</p><p>Now, with this knowledge, let’s dive into specific properties you can use. For demonstration purposes, I’ll use a layout of boxes from the <a href="https://codepen.io/Dromedian_sk/pen/RwPyewQ?editors=1100">code snippet in CodePen</a>.</p><h3>The ‘display’ Property</h3><p>Before you apply Flexbox, the parent component (the flex container) needs to have thedisplay property set to flex or inline-flex.</p><p>What’s the difference?</p><p>There’s absolutely none when it comes to the effect on flex items. display: inline-flex makes the flex container display inline. A similar comparison can be made between display: inline-block and display: block.</p><h3>‘flex-direction’</h3><p>This property establishes the main axis, thus defining the direction flex items are placed in the flex container. Flexbox is (aside from optional wrapping) a single-direction layout concept. Think of flex items as primarily laying out either in horizontal rows or vertical columns.</p><p>flex-direction offers the following four values you can set to the flex container: row, column, row-reverse, and column-reverse.</p><p>The aptest example, how each value affects the view, is show in this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*ONGIuAkxpgCsxcZEziweyg.jpeg" /><figcaption>The flex-direction property</figcaption></figure><h3>‘flex-wrap’</h3><p>The flex-wrap property is for setting the flex container to wrap or not to wrap items in one line. Available values are wrap, no-wrap, and wrap-reverse. By default, flex items will try to wrap into one line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*6psrba_BiLGA-Ybd05z13Q.jpeg" /><figcaption>The flex-wrap property</figcaption></figure><h3>Practice Exercise #1</h3><h4>Challenge</h4><p>Let’s demonstrate flex-direction and flex-wrap in the following example, and then we’ll move on. I want to have boxes in a row, and they should wrap if needed, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*VUlVtbd1fW8t-x_ZtCXihA.png" /></figure><h4>Solution</h4><p>Here’s the code from the flex container:</p><pre>.flex-container {<br>  height: 200px;<br>  <strong>display: flex;<br>  flex-direction: row;<br>  flex-wrap: wrap;</strong><br>}</pre><p><strong>Tip:</strong> You can also use theflex-flow property, which is just a shorthand of flex-direction and flex-wrap, and they, together, define the flex container’s main and cross axes.</p><pre>flex-flow: &lt;‘flex-direction’&gt; || &lt;‘flex-wrap’&gt;</pre><p>So we could apply it in the following way:</p><pre>.flex-container {<br>  height: 200px;<br>  <strong>display: flex;<br>  flex-flow: row wrap;</strong><br>}</pre><h3>‘justify-content’</h3><p>This defines the alignment along the main axis. It helps distribute extra free space leftover when either all the flex items on a line are inflexible — or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line.</p><p>In this property, there are five values available. The following picture depicts the behavior of each value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*2a1EdASNCCNlA62qskhsRQ.jpeg" /><figcaption>The justify-content property</figcaption></figure><h3>‘align-items’</h3><p>This property is very similar to justify-content — except it aligns items on the cross axis and not the main axis. Here’s a picture with all available values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*_FdCfr_DJt8a8_e7Am3WZw.jpeg" /><figcaption>The align-items property</figcaption></figure><h3>‘align-self’</h3><p>This allows the default alignment (or the one specified by align-items) to be overridden for individual flex items. Available values are the same as in the align-items property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*0qKvuBtJAd36NZ9io7uGDw.jpeg" /><figcaption>The align-self property</figcaption></figure><h3>Practice Exercise #2</h3><h4>Challenge</h4><p>The theory I explain above seems to be obvious in terms of how items should behave. However, if you want to avoid unexpected behavior, you have to observe a few principles in Flexbox. Let’s demonstrate it in the example.</p><p>We want to position our green boxes in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4L2jzhnul8_V2JcDp6TMpA.png" /></figure><p>And here’s our HTML structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a377aca889798741997709685ef03ec/href">https://medium.com/media/8a377aca889798741997709685ef03ec/href</a></iframe><h4>Solution</h4><p>According to the theory, we can use justify-content and align-items on the flex-container, so we’ll center it to the middle along the main and cross axes:</p><pre>.flex-container {<br>  <strong>display: flex;<br>  justify-content: center;<br>  align-items: center;<br></strong>}</pre><p>But this isn’t enough.</p><p>In this case, the flex items are aligned to the center only along the main axis because the flex container and wrapper are adiv element, which is set to width: 100% by default.</p><p><strong>Note:</strong> Keep in mind that when aligning, flex-container must have always width and height defined.</p><p>Now the only thing we need is to align the boxes with the first-column class at the top and the boxes with thethird-column class at the bottom. We can accomplish that with thealign-self property:</p><pre>.first-column {<br>  <strong>align-self: flex-start;</strong><br>}</pre><pre>.third-column {<br>  <strong>align-self: flex-end;</strong><br>}</pre><h3>‘flex-grow’ and ‘flex-shrink’</h3><p>With the flex-grow property, you can handle cases when you need some flex items to grow. It accepts a unitless value that serves as a proportion. It controls how much of the available space inside of the flex-container that the item should take.</p><p>If all items have flex-grow: 1, the remaining space in the flex-container will be distributed equally to all children. If one of the children has a value of 2, the remaining space would take up twice as much space as the others (or it’ll try to, at least).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*mnXCgyBJuw_OvW7mnhUU0g.jpeg" /></figure><p><strong>Note</strong>: Negative numbers are invalid.</p><p>flex-shrink is just the opposite of flex-grow. You can define a flex-item to shrink if necessary, so the item will take less space then others.</p><h3>‘flex-basis’</h3><p>This property defines the size of the flex-item along the main axis of the flex-container before the remaining space is distributed. It can be a length (e.g. 20%, 5rem, etc.), auto, or content.</p><p>The auto keyword means “look at my width or height property.” The extra space will be distributed based on its flex-grow value.</p><p>The content keyword means “size is based on the item’s content.”</p><p>If set to 0, the extra space around content isn’t factored in. Check this <a href="https://www.w3.org/TR/css-flexbox-1/images/rel-vs-abs-flex.svg">graphic</a>.</p><h3>‘flex’</h3><p>This property is just a shorthand of the previous three properties combined. The second and third parameters (flex-shrink and flex-basis) are optional. The default is flex: 0 1 auto, but if you set it with a single number value, it’s like &lt;number&gt; 1 0.</p><p><strong>Note:</strong> It’s recommended you use this shorthand property rather than set the individual properties. The shorthand sets the other values intelligently.</p><h3>Practice Exercise #3</h3><p>This challenge is maybe the most useful and the most difficult at the same time.</p><h4>Challenge</h4><p>Let’s say we can use Flexbox only, and we want our green boxes to have three rows with two columns. So it should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbcYZrYscG4MT0Z8FfJ2Uw.png" /></figure><h4>Solution</h4><p>As you can see from the picture, we first need to tell flex-container to wrap items. This we already know:</p><pre>.flex-container: {<br>  display: flex;<br>  <strong>flex-wrap: wrap;<br></strong>}</pre><p>And now the funny part. With knowledge about flex properties, we can solve it with one line of code:</p><pre>.flex-item {<br>  <strong>flex: 1 0 50%;</strong><br>}</pre><p>1 is for flex-grow, 0 is for flex-shrink, and 50% is for flex-basis. You might think this will always work — but there’s a catch.</p><p>In flex-basis, you need to count including the item’s border and margin (from both sides!), because they’re extending its width.</p><p>Here’s a code example of how it can look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eb0d9f0be270f53e206528960d004c5/href">https://medium.com/media/8eb0d9f0be270f53e206528960d004c5/href</a></iframe><h3>Conclusion</h3><p>With knowledge of Flexbox, I’m pretty sure you’ll become a better front-end developer, mostly in terms of styling components. Knowledge of CSS is underestimated in most projects, but your app won’t attract the eyes of potential customers if it looks awful and can’t be used on mobile screens.</p><p>I’d say the fluent responsiveness of apps is crucial these days.</p><p>If you want to position a single component, maybe Flexbox would be an overkill for your needs. For that case, you can use the position property, which I explain here:</p><p><a href="https://medium.com/better-programming/how-to-use-the-position-property-in-css-926a3ea8a9b2">How to Use the position Property in CSS</a></p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca0ffdf770c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/a-comprehensive-guide-to-flexbox-ca0ffdf770c6">A Comprehensive Guide to Flexbox</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[How to Use the position Property in CSS]]></title>
            <link>https://medium.com/better-programming/how-to-use-the-position-property-in-css-926a3ea8a9b2?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/926a3ea8a9b2</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 04:01:38 GMT</pubDate>
            <atom:updated>2020-04-08T17:07:46.184Z</atom:updated>
            <content:encoded><![CDATA[<h4>A basic principle of CSS layout demonstrated in simple examples with boxes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bkFrE6-0rTkwHwIh" /><figcaption>Photo by <a href="https://unsplash.com/@aleksdorohovich?utm_source=medium&amp;utm_medium=referral">Aleks Dorohovich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>CSS isn’t popular among most developers and knowledge of this technology tends to be underestimated. That’s why there is a lot of frustration when styling elements.</p><p>It can be particularly tricky to style elements that have an ambiguous relation to other components in the DOM. In order to understand how CSS positioning works, you should get to know the basic principles.</p><p>The appropriate position of an element is case-dependent. You might want to move only a particular element with its children from the default position. In that case, it’s a good idea to use the position<em> </em>property.</p><h3>The position Property</h3><p>This property helps to manipulate the location of the selected element. There are five different position values:</p><ul><li>static</li><li>relative</li><li>fixed</li><li>absolute</li><li>sticky</li></ul><p>Now you should keep in mind that elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. How they behave also depends on position value, which is the most confusing part for developers.</p><p>Let’s master these values with simple examples.</p><h3>position: static</h3><p>This value is set for all HTML elements by default. It means they are positioned according to the normal flow of the page.</p><p>Also, keep in mind that elements with the static position are not affected by the top, bottom, left, and right properties.</p><p>Now, let’s look at a simple example with one container and three boxes inside:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c7f5b37126eee8c58c377ee635de552/href">https://medium.com/media/0c7f5b37126eee8c58c377ee635de552/href</a></iframe><p>And here is our CSS:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7fe164b5c7149cbe8655b165642146b/href">https://medium.com/media/a7fe164b5c7149cbe8655b165642146b/href</a></iframe><p>As stated above, position: static is set as a default value of each element. For this reason, it’s not necessary to add it to the CSS file. Boxes are stacked according to the normal flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kT0mO_mRHq24rK4RZHdXQg.png" /><figcaption>position: static</figcaption></figure><h3>position: relative</h3><p>An element with position: relative is positioned relative to its normal position.</p><p>Now, let’s try to position our yellow box next to the green boxes. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uKH3H8vCNjG1aleZSf0yw.png" /><figcaption>position: relative</figcaption></figure><p>Because we want to move the yellow box from its normal position, we have to adjust CSS in the following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0f04017fc12737852616d3ef2f91be1/href">https://medium.com/media/b0f04017fc12737852616d3ef2f91be1/href</a></iframe><p>Try to play around with boxes and check out their behavior.</p><h3>position: fixed</h3><p>An element with position: fixed is positioned relative to the viewport. This means it always stays in the same place even if the page is scrolled.</p><p>An important aspect to keep in mind is that the element is removed from the flow of the document, so it does not leave a gap on the page where it would normally have been located.</p><p>Let’s give a fixed position to our yellow box:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b4826fd5421eddacf1bdb12f9a4921f/href">https://medium.com/media/5b4826fd5421eddacf1bdb12f9a4921f/href</a></iframe><p>And here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dz7w7UwUw0Hz9JN5O31g0g.png" /><figcaption>position: fixed</figcaption></figure><p>Now, if you scroll the page, the yellow box will stay in the viewport. As an example, this is how a website’s navbar should be used. Also, green boxes are stacked to the top because of the aspect mentioned earlier.</p><h3>position: absolute</h3><p>An element with position: absolute is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).</p><p>An element withposition: absolute is removed from the flow of the document and other elements will behave as if it’s not even there while all the other positional properties will work on it.</p><p>Note: If an absolute-positioned element has no positioned ancestors, it uses the document body and moves along with page scrolling.</p><p>Now, let’s modify our example by moving one green box inside the yellow box.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/223558e264533060fcaf14e45c9aeb96/href">https://medium.com/media/223558e264533060fcaf14e45c9aeb96/href</a></iframe><p>And let’s assume the yellow box has position: fixed and right: 10px(same as in the example above).</p><p>What if we wanted to move the inner green box below the yellow box? At the same time, we’d like to not modify the HTML file.</p><p>We can do it with by giving position: absolute to the green box:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6552caf53f9c6b60e04a8645a965ef3/href">https://medium.com/media/e6552caf53f9c6b60e04a8645a965ef3/href</a></iframe><p>If you scroll the page, both boxes will stay in the viewport.</p><h3>position: sticky</h3><p>This value is rather experimental because it’s not supported in all browsers yet. An element with position: sticky is positioned based on the user&#39;s scroll position.</p><p>A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport. Then it &quot;sticks&quot; in place (like position: fixed).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e859fb1625eaadef783e10b67f4acf9/href">https://medium.com/media/4e859fb1625eaadef783e10b67f4acf9/href</a></iframe><h3>Space for Practice</h3><p>Getting to know CSS can sometimes be very tricky and frustrating. The only way how to master the principles is by practicing. Write a lot of code, create simple projects, style elements as you wish.</p><p>If you’d like to sharpen your positioning skills, feel free to <a href="https://codepen.io/Dromedian_sk/pen/OJVbYVY">play with the boxes</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=926a3ea8a9b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-use-the-position-property-in-css-926a3ea8a9b2">How to Use the position Property in CSS</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[React Testing: Get Started With Cypress.io]]></title>
            <link>https://medium.com/better-programming/react-testing-get-started-with-cypress-io-a19b6eb6332a?source=rss-515feaa3ce20------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19b6eb6332a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Miroslav Pillár]]></dc:creator>
            <pubDate>Mon, 17 Feb 2020 03:00:23 GMT</pubDate>
            <atom:updated>2020-04-08T17:07:15.093Z</atom:updated>
            <content:encoded><![CDATA[<h4>Write meaningful end-to-end tests with minimal effort</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KkA0-ia3Gd_VrGdl" /><figcaption>Photo by <a href="https://unsplash.com/@vishnurnair?utm_source=medium&amp;utm_medium=referral">Vishnu R Nair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>Developers hate writing tests. It takes time and, in the end, it doesn’t provide additional value to the customer. Furthermore, it tends to be boring.</p><p>With Cypress, I’ve discovered a brand new perspective on testing. It’s easier to understand, more effective, and much more entertaining.</p><p>I’ll show you an implementation of Cypress in a React app, which you can clone from <a href="https://github.com/Dromediansk/countries-app-blog/tree/react-router-implementation">this Github repo</a>. Our goal is to test the main functionality of the app — that means writing tests for navigation links, a request to the API, and filter functionality.</p><p>Note: If you’re interested in building the whole app from scratch, you can start with the story <a href="https://medium.com/better-programming/some-best-practices-for-building-a-react-app-with-hooks-d6157494f5c1">Some Best Practices for Building a React App With Hooks</a>.</p><h3>What You Should Know About Cypress</h3><p>It’s an E2E testing tool, which simplifies the process of writing tests. The purpose of those tests is to exercise a complete production-like scenario. This means we’re able to simulate user behavior and cover all required functionalities.</p><p>Cypress has a nice GUI where you can see individual tests as well as how it looks like in your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQGS9eJdVU-2ncY1MfYGzA.png" /><figcaption>Cypress test runner example</figcaption></figure><p>These are the highlights when using Cypress:</p><ul><li>Tests are easy to read and write (similar to plain English).</li><li>The test runner uses a web browser, so you can see what functionality is tested in real time.</li><li>You can simultaneously develop your app while tests are running.</li><li>Readable error messages help you to debug quickly.</li><li><a href="https://www.cypress.io/">Well-worked-out documentation</a>.</li></ul><h3>Installing Cypress</h3><p>Now, let’s focus on the practical part. You can clone <a href="https://github.com/Dromediansk/countries-app-blog/tree/react-router-implementation">the Github repo</a> and install Cypress with this command:</p><pre>npm install cypress --save-dev</pre><p>After a while, it will add a new cypress.json file and cypress folder into the root directory. We will store all our tests in cypress/integration/examples.</p><p>You can open Cypress with this:</p><pre>./node_modules/.bin/cypress open</pre><p>I know, this is an awful way to launch Cypress every time. I would forget the command immediately. Fortunately, you can simplify it by adding the following npm script into package.json:</p><pre>&quot;scripts&quot;: {     <br>    &quot;cypress&quot;: &quot;cypress open&quot;   <br>}</pre><p>And then you can open Cypress with just npm run cypress.</p><h3>Telling Cypress to Visit the Website</h3><p>Before we write tests, we need to command Cypress to visit our website. So firstly, let’s define baseUrl in the cypress.json:</p><pre>{<br>    &quot;baseUrl&quot;: &quot;http://localhost:3000&quot;<br>}</pre><p>baseUrl is the URL used as a prefix for the <a href="https://docs.cypress.io/api/commands/visit.html">cy.visit()</a> or <a href="https://docs.cypress.io/api/commands/request.html">cy.request()</a> command’s URL. It’s a good practice to store our base URL so it’s accessible in all our tests.</p><p>And now, we can tell Cypress to visit the website. In /cypress/integration/examples, we can create a new spec file, call it routeNavigation.spec.js, and write the following command:</p><pre>cy.visit(&quot;/&quot;);</pre><p>All of Cypress’ functionality is available under the global cy object. Try to run this test to see the result.</p><h3>Testing Navigation Links</h3><p>If a user wants to use our app, the navigation links are one of the core functionalities that must work. It’s also appropriate to write simple tests in the beginning and get to know the syntax.</p><p>So let’s write the test in routeNavigation.spec.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dec2a9e7a9f930ace59b3637664bbd9/href">https://medium.com/media/6dec2a9e7a9f930ace59b3637664bbd9/href</a></iframe><ul><li>In before() on line 2, we can implement code that is executed before any tests run — in our case visiting the default route of the website.</li><li><a href="https://docs.cypress.io/api/commands/get.html#Syntax">cy.get()</a> is used for selecting the proper element. We’re searching for the a element, which is a child of the class nav-list-item class.</li><li>eq(1) stands for selecting the second element. Counting starts at zero.</li><li>We’re simulating the click event on the selected element.</li><li>Finally, with <a href="https://docs.cypress.io/api/commands/location.html#Syntax">cy.location</a>, we’re checking if pathname includes /data in the address bar.</li><li>timeout is an optional setting with which you can pass the amount of time to wait for resolve. I’m pretty sure that 99% of users will leave the website after one minute of waiting.</li></ul><p>In a similar way, you can write tests for every other route. Feel free to try it out on your own and play around.</p><h3>Testing Request to the API</h3><p>Our goal is to check whether we get a response with status 200 and also receive the response with countries’ data.</p><p>In general, testing requests can be executed with the <a href="https://docs.cypress.io/api/commands/request.html#Syntax">cy.request()</a> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a249f069131b8a005b319eee5ef24c4e/href">https://medium.com/media/a249f069131b8a005b319eee5ef24c4e/href</a></iframe><h3>Testing Focus of the Input</h3><p>The goal of this test is to check if the input for searching by country is focused when a user visits the page.</p><p>Firstly, make sure the input with the placeholder country has set the prop autofocus in AdvancedFilter.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbbd76965973544dc87e6a99b0a96f92/href">https://medium.com/media/fbbd76965973544dc87e6a99b0a96f92/href</a></iframe><p>Now we can write a test to check if it’s working. Because we’re testing another functionality, let’s create a new file for that and name it filtering.spec.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85d6223f9912f06c2cbb1b0aa2191aaf/href">https://medium.com/media/85d6223f9912f06c2cbb1b0aa2191aaf/href</a></iframe><ul><li>Similarly to the previous test file, we tell Cypress to visit the required route in the first place.</li><li>In the test, we select the input by name prop and check if it’s in focus.</li></ul><h3>Testing Filter Functionality</h3><p>I’d consider filtering a crucial part of our app. If it weren’t functional, the app&#39;s purpose would be lost. Hence we should first test if searching by country is working.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/078bddc86c1a12fa359eb2d2d4066634/href">https://medium.com/media/078bddc86c1a12fa359eb2d2d4066634/href</a></iframe><p>The goal of this test is to check if the value changes when a user inputs some text (e.g. “us”). After that, we also expect that the filtered countries will match the value (8).</p><p>Of course, there are many options on how to enhance this test, so feel free to play around. Also, you can write tests for other inputs on your own.</p><p>Here’s the <a href="https://github.com/Dromediansk/countries-app-blog/tree/testing">final version of the GitHub repo</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzvsCpkKn8qJDUby46oSdg.png" /><figcaption>Final version</figcaption></figure><h3>Final Words</h3><p>I hope you are at least as amazed by Cypress as I am. It’s a great E2E testing tool suitable for all kinds of technologies — not only for React. It’s fast, tests are easy to read, and it has <a href="https://docs.cypress.io/guides/overview/why-cypress.html#In-a-nutshell">great documentation</a>.</p><p>However, a good developer should learn <em>how </em>and <em>what </em>to test in the app. It’s simply a waste of time if you write meaningless tests that increase code coverage but don’t test the true functionality.</p><p>Besides, if you want to do proper tests, you have to learn the corresponding syntax, matchers, etc., which of course takes more time. Therefore, it’s wise to take into consideration the overall scope of testing before you start spending your time on writing tests.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19b6eb6332a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/react-testing-get-started-with-cypress-io-a19b6eb6332a">React Testing: Get Started With Cypress.io</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>
    </channel>
</rss>