<?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 Мihail Gaberov on Medium]]></title>
        <description><![CDATA[Stories by Мihail Gaberov on Medium]]></description>
        <link>https://medium.com/@mihailgaberov?source=rss-73c3949b96a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9hmq4ab9GeEL-FC5Gd-Tnw.jpeg</url>
            <title>Stories by Мihail Gaberov on Medium</title>
            <link>https://medium.com/@mihailgaberov?source=rss-73c3949b96a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:58:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mihailgaberov/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[How I build a desktop chat app with CometChat and NW.js (and how you can too)]]></title>
            <link>https://itnext.io/how-i-build-a-desktop-chat-app-with-cometchat-and-nw-js-and-how-you-can-too-fb03cb685c0d?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb03cb685c0d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nwjs]]></category>
            <category><![CDATA[desktop]]></category>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[chat-apps]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 12:56:27 GMT</pubDate>
            <atom:updated>2019-09-22T12:56:27.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Chat Screen" src="https://cdn-images-1.medium.com/max/590/0*U9bmDxD3rDwp9ic_.png" /></figure><p>This is not your typical “<em>paste this here</em>” and “<em>paste that there</em>”-type tutorial (you can find plenty of those here on <a href="https://www.cometchat.com/tutorials/desktop-chat-app-tutorial/">cometchat.com/tutorials</a>). While those tutorials certainly have merit, I am going to share my thought process from beginning to end.</p><p>The application I built is simple enough. When someone loads the app, they are prompted to enter their username and begin chatting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*ZTfdGRKfalLDv19t.png" /></figure><p>The application ultimately runs on Node with help from NW.js (previously known as node-webkit). NW.js is advantageous because it enables us to code cross-platform desktop applications using our favorite web technologies. For this application, I chose to use React and Redux.</p><p>The back-end logic — from sending and receiving messages in real-time to populating what I call the “participant list” — is powered by CometChat. You will learn more about <a href="https://cometchat.com/pro">CometChat</a> as you read on.</p><p>This post is not intended to be a walkthrough. Although I will be explaining the technical components of this application, my main ambition is to help you think through a solution from beginning to end. Hopefully, when you finish this post you’ll be a slightly better developer and consider CometChat for your growing tool belt.</p><h3>Just want the example code?</h3><p>You may see the source code <a href="https://github.com/mihailgaberov/desktop-chat-nw">here</a>. There is also a detailed <a href="https://github.com/mihailgaberov/desktop-chat-nw/blob/master/README.md">README</a>, where you will find all the information you need to install, run and test the app.</p><p>Because the desktop app is built using web technologies, it is entirely possible to run it in your browser. Towards the end of this post, I will show you how to deploy the app on Netlify.</p><h3>Planning</h3><p>In this section, we have to decide what components will we need to build. What functionality will they have? In other words, what are the questions we need to answer, to plan the building process?</p><p>Let’s step back for a while and think. Try asking yourself the questions who will take us to the structure we need for our app.</p><p><em>Below I am going to lay out my questions and the answers. This is the process of the actual building the structure of the app, but in your head first. Keep in mind that it happens very often such that when answering a question new questions appear. This was the case with me as well.</em></p><p><strong>Questions:</strong></p><ul><li>What am I doing? 😆</li><li>What kind of app am I going to be building?</li><li>What are the most common components, such an app needs to have?</li><li>How do the app’s components interact with each other?</li><li>What level of completion am I aiming for — (demo apps are not supposed to be fully featured)?</li></ul><p><strong>Answers</strong> (following the order of the questions):</p><ul><li>This is the most neglected question that many people forget to think about. <em>When one can step aside first and give a clear answer to this question, his path for future developments becomes settled</em>. In my specific case the answer I got sounds something like this — “I am thinking about building a chat app. This app should serve as a tutorial demo app. It will have to provide basic functionality for ‘having a chat’ by using CometChat API. It should run on a desktop”. The styling and specific details about what goes where will come later in the process.</li><li>A chat app that will run on desktop and serve as a demo for this tutorial.</li><li>To give a proper answer to this question, a non-familiar person would have to do some research first. Take a look at real-world chat applications. Make notes of what features they have. How are they put them in place, how do they interact between them and with the users of the app. In my case, I had some <a href="https://mihail-gaberov.eu/how-i-build-chat-app-with-react-and-typescript-part1/">previous experience</a> and got, more or less, the idea of what I need.</li><li>The interaction between the components would be pretty straight forward. The user should be able to use the main component that is a text input and a button to send messages. And a sidebar component to see the other chat participants.</li><li>The demo app should provide basic chat functionality — send and receive real-time messages. And be able to run on a desktop (without a browser).</li></ul><h3>Features</h3><p>I have decided to implement the following features to the demo app:</p><ul><li>Send with Enter key</li><li>A sidebar with names and last active time</li><li>Welcome screen with input and validation with error messages</li><li>Chat area with auto-scroll to bottom</li><li>Chat message and time of sending.</li></ul><h3>Front End — React</h3><p>We are going to use <a href="https://reactjs.org/">React</a> to build our user interface. Below, I am going to list the components I have created and a short explanation about each of them:</p><ul><li><a href="https://github.com/mihailgaberov/desktop-chat-nw/tree/master/src/components/ChatPane">ChatPane</a> — this is the main container-like component that contains the Participants and Conversation components and passes the data they need to visualize.</li><li><a href="https://github.com/mihailgaberov/desktop-chat-nw/blob/master/src/components/Conversation/Conversation.jsx">Conversation</a> — this is the component responsible for typing and sending chat messages.</li><li><a href="https://github.com/mihailgaberov/desktop-chat-nw/blob/master/src/components/Footer/Footer.jsx">Footer</a> — displays a simple footer message, containing the app name and version, as defined in package.json file.</li><li><a href="https://github.com/mihailgaberov/desktop-chat-nw/blob/master/src/components/Header/Header.jsx">Header</a> — header component holding the application menu bar.</li><li><a href="https://github.com/mihailgaberov/desktop-chat-nw/blob/master/src/components/MenuAppBar/MenuAppBar.jsx">MenuAppBar</a> — application menu bar component, simulating how a real menu bar would look like. The hamburger menu on the left and the profile dropdown menu on the right are fake — clickable, but not functional.</li><li><a href="https://github.com/mihailgaberov/desktop-chat-nw/blob/master/src/components/Messages/Messages.jsx">Messages</a> — a container component, holding a message itself — it has the name of the sender, the message content and the time of sending.</li><li><a href="https://github.com/mihailgaberov/desktop-chat-nw/tree/master/src/components/Participants">Participants</a> — this component shows the name of a chat member and the time when he joined.</li><li><a href="https://github.com/mihailgaberov/desktop-chat-nw/tree/master/src/components/Welcome">Welcome</a> — this component is responsible for displaying the login page — the starting point of our app, where we have logic related to checking for certain allowed usernames and storing them to the local storage for later use. I also implemented basic error handling logic, which shows an error when the selected username is not correct, as per CometChat API (in this specific case for our demo) registered usernames — superhero1, superhero2 and so on till 5.</li></ul><p>Here a visual representation of the app components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*6eBPTO7BwulQf3-b.png" /></figure><h3>State Management — Redux</h3><p>Every modern application these days has a state. Place in the memory where the application is storing certain data for later use. For our application state management, we use <a href="https://redux.js.org/">Redux</a>. Of course, for a simple app like this, we could go without using Redux at all. But, from the learning point of view (<em>after all we all do this for learning new stuff, right?</em>), I think it would be nice to see the whole cycle of sending a request to an API, going through a middleware (redux-thunks) and getting the response recorded to the state. And we will manage this state by using Redux.</p><h3>How it works</h3><p>The main building blocks in a Redux app are called reducers — small functions used for managing the state. Simply said, what they do is accepting the old state object as input and, depending on certain actions (which are also passed in the same input), returning new state object. The new state could be changed in full or just partially.</p><p>In our app, we have three simple reducers, which are responsible for those parts of the state, responsible for the users’ list, the login process and sending/receiving messages. All of them can be seen in <a href="https://github.com/mihailgaberov/desktop-chat-nw/tree/master/src/reducers">/src/reducers</a> folder, along with a <a href="https://github.com/mihailgaberov/desktop-chat-nw/blob/master/src/reducers/initialState.js">file</a> containing the initial state of our app.</p><p>Redux, as state management library, can be used with any other UI framework, practically every app that needs to have a state can benefit from using Redux. If you want to go deeper, start from their website and follow along.</p><h3>Side Effects Handling — Redux Thunks</h3><p>One of the best-known approaches for managing side effects in a redux app is called <a href="https://github.com/reduxjs/redux-thunk">redux-think</a>. This is what we use in our application as well. If you want to learn more details about redux thunks and how to use them, I recommend their website as a starting point and then build a small application, like this one for example :).</p><p>In our project, in <a href="https://github.com/mihailgaberov/desktop-chat-nw/tree/master/src/actions">/src/actions folder</a>, is where I put the thunks used in the demo application. And in <a href="https://github.com/mihailgaberov/desktop-chat-nw/tree/master/src/store">/store</a> directory is where the configurations for the redux store live.</p><h3>Make it desktop — NW.js</h3><p>The part of our application that makes it possible for our app to run on desktop is taken care of by a library called <a href="https://nwjs.io/">NW.js</a>. Remember that we are building a desktop application. Exactly the desktop part is going to be implemented via NW.js. Similar to <a href="https://electronjs.org/">Electron</a>, another library for building desktop applications, NW.js provides a way to the developers to use their web skills to build applications that can run on a desktop. This means you can still use your JavaScript/React skills when building an app and then leverage the power of the desktop operating system via Nw.js APIs. In other words, Nw.js gives you the ability to make a skeleton app, which can be “filled” with your UI, no matter what library you have used to create it. And the best thing is that such an app has access to Node.js/NW.js APIs and the DOM in the same JavaScript context.</p><p>Since we mentioned the other big player in the field of building cross-platform desktop apps, let me give you a brief comparison between the two.</p><h3>Nw.js vs Electron</h3><ul><li>Entry of Application</li></ul><p>— In NW.js the main entry point of an application is a web page or a JS script. You specify an HTML or js file in the package.json and it is opened in a browser window as the application’s main window (in case of an HTML entry point) or the script is executed.</p><p>— In Electron, the entry point is a JavaScript script.</p><ul><li>Build System</li></ul><p>— Nw.js uses Chromium</p><p>— Electron uses <a href="https://github.com/electron/libchromiumcontent">libchromiumcontent</a> to access Chromium’s Content API. libchromiumcontent is a single shared library that includes the Chromium Content module and all of its dependencies.</p><ul><li>Node Integration</li></ul><p>— In NW.js, the Node integration in web pages requires patching Chromium to work.</p><p>— In Electron uses a different way to integrate the libuv loop with each platform’s message loop to avoid hacking Chromium.</p><ul><li>Multi-context</li></ul><p>— Because of how NW.js was implemented concepts of Node context and web context were invented.</p><p>— By using the <a href="https://github.com/nodejs/node-v0.x-archive/commit/756b622">multi-context</a> feature of Node, Electron doesn’t introduce a new JavaScript context in web pages.</p><h3>Chat — CometChat</h3><p>The usage of CometChat API is pretty straight-forward. It’s a RESTFull API, on which is built another layer of abstraction — CometChat SDK. It allows us to call directly exposed methods for different actions we might want to perform, such as send. Here an example of such a method:</p><pre>return CometChat.sendMessage(textMessage).then(    <br>  message =&gt; {      <br>    console.log(&quot;Message sent successfully:&quot;, message);      <br>    return message;<br>  }, <br>  error =&gt; {      <br>    console.log(&quot;Message sending failed with error:&quot;, error);    <br>  }<br>);</pre><p>You may see all the Chat API logic in <a href="https://github.com/mihailgaberov/desktop-chat-nw/tree/master/src/chat-api">/src/chat-api</a> folder. There you will also see the mocks I created, which allow us to test our app without real connection to the API.</p><h3>Improvements</h3><p>Every project deserves some thoughts after finishing the first phase. One part of this thought process would be dedicated to how it went, what was good and bad, and what might be done better. And one part would be dedicated to thinking about possible improvements. Here are a few ideas for our case. If someone goes to this direction and implement any of these for real, please do not forget to let me know :)</p><ul><li>Waiting animation for when loading the chat history and the user list</li><li>Option for skipping the login screen, if already logged</li><li>Option for sending invitations to new users</li><li>Option for seeing the status of a message — sent, received, read</li><li>Emojis support</li><li>Inline links/images/video support, such that the user can see them interpreted — playing video, rendered image or web page to which a link is pointing. I have added these as <a href="https://github.com/mihailgaberov/desktop-chat-nw/issues">issues in my GitHub</a>, in case anyone wants to take a look.</li></ul><h3>Deploy on Netlify</h3><p>To deploy your application to Netlify platform you need to create an account first. Go to <a href="https://www.netlify.com/">their website</a> and sign up for new account. After that go ahead and login. While still under Sites section, you should see a button for deploying new site from Git.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*bRgJcT3ouG-W87fe.png" /></figure><p>Click it and follow the steps to create a new site for deployment from your GitHub repositories. Your process should be similar to what is shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*ZIU6k7ux-y75B5GA.png" /></figure><p>Now, the last step before having your app deployed is to make sure you have the correct build commands and environment variables in place. To do that, after you create your site for deployment, go to <strong>Build &amp; deploy</strong> settings screen and enter the following (don’t forget to use your repo URL):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*-ppF9uk9HCvqXuTs.png" /></figure><p>Under <strong>Environment</strong> section is where you need to enter the environment variables as defined in your .env file. Here is how it looks mine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*xOfl1HjZjRc3Msc6.png" /></figure><p>Note: <em>I have erased the values as this is supposed to be private info and you should not share yours as well.</em></p><p>That should be enough for you to have your app deployed on Netlify. Keep in mind the <strong>Deploys</strong> default settings are set to ‘auto publishing’, which means that it will trigger a deploy on each commit you do to the <strong>master branch</strong> in your repo. This is the place where you can trigger a deploy manually as well. This is how my <strong>Deploys</strong> screen looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*ZWH669TC-yyTYrxp.png" /></figure><h3>Conclusion</h3><p>In this tutorial, we saw how can we leverage our web development skills to create applications that can run on a desktop. What we built is a demo application, that lacks a lot of a fully-featured-production-ready app features, but when one wants to learn and share, this would do the job. If you would like to deepen your knowledge in this direction, I would recommend you to try to improve it, by implementing features that are more likely to be seen in a real desktop application.</p><p>There are plenty of opportunities to explore out there, I hope this tutorial entertained you enough to keep your flame of curiosity burning even more.</p><p>🔥 Thanks for reading! 🔥</p><p><strong>Notes:</strong></p><ul><li>In order to use Nw.js DevTools you need to install the SDK build — <a href="https://nwjs.io/downloads/">https://nwjs.io/downloads/</a> — version 0.38.2 or higher.</li></ul><p><strong>Resources:</strong></p><ul><li><a href="https://daveceddia.com/what-is-a-thunk/">Q: What is a ‘thunk’? A: The sound your head makes when you first hear about redux-thunk. Ok sorry, that was awful. But…daveceddia.com</a></li><li>[book] Cross-Platform Desktop Applications: Using Node, Electron, and NW.js</li><li>[book] Cross-platform Desktop Application Development: Electron, Node, NW.js, and React</li><li><a href="https://github.com/reduxjs/redux-thunk">Thunk middleware for Redux</a></li><li><a href="https://reactjs.org/docs/hooks-reference.html#useref">https://reactjs.org/docs/hooks-reference.html#useref</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb03cb685c0d" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-i-build-a-desktop-chat-app-with-cometchat-and-nw-js-and-how-you-can-too-fb03cb685c0d">How I build a desktop chat app with CometChat and NW.js (and how you can too)</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualize Pancakes Algorithm with React and Popmotion.io]]></title>
            <link>https://itnext.io/visualize-pancakes-algorithm-with-react-and-popmotion-io-91683b554609?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/91683b554609</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Tue, 03 Sep 2019 11:36:50 GMT</pubDate>
            <atom:updated>2019-09-03T11:36:50.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*sqTIKWDeYn37YgTpfck4Ew.png" /><figcaption>Pancakes Algorithm Visualization</figcaption></figure><p>What you are going to see below was suppose to be part of my solution to an exercise given in a coding challenge. It was several months ago and I had signed in for it. Due to unforeseen factors, I haven’t gone to the end. Now, after that time and the challenge finished, I can share it here.</p><p>This is not going to be a step-by-step tutorial. Rather a quick review of how can we use frameworks like React and Popmotion.io, and an algorithm. And create a nice visualization of that very same algorithm. Somehow it feels nice! 🤓</p><p>The so called <a href="https://en.wikipedia.org/wiki/Pancake_sorting">Pancakes Sorting Algorithm</a> is famous (or not?) sorting algorithm, that you can read a lot on internet, if interested. Its nature is out of the scope of this article. Here we only see it in action with nice animations, thanks to <a href="https://popmotion.io/pose/">Popmotion.io</a>.</p><p>Here is the <a href="https://pancakes-algorithm.herokuapp.com/">live demo</a> you can play with. And <a href="https://gitlab.com/mihailgaberov/pancake-algorithm-visualizer">here</a> is where you can find the source code of it. Feel free to check it out and take a closer look. You might try to amend the animations I did. I would be more than interested to see your versions :)</p><p>That was all. Nice and short, perfect for the summer! ☀️ 🏖</p><p>🔥 Thanks for reading! 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91683b554609" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/visualize-pancakes-algorithm-with-react-and-popmotion-io-91683b554609">Visualize Pancakes Algorithm with React and Popmotion.io</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize your JavaScript app by using service workers]]></title>
            <link>https://itnext.io/optimize-your-javascript-app-by-using-service-workers-3e2ba71b90d6?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e2ba71b90d6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[workers]]></category>
            <category><![CDATA[services]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Tue, 03 Sep 2019 10:05:39 GMT</pubDate>
            <atom:updated>2019-09-03T10:05:39.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JwJUzDI5NKUIKIbAvZmKDQ.jpeg" /><figcaption>A nice image used for demonstration of SW work.</figcaption></figure><p>Every now and then we hear about optimizing something. There are different kinds of optimizations we could do to make our apps faster and more efficient. To save time or memory. This article will cover one of those methods — s<em>ervice </em>w<em>orkers.</em></p><h3>TL;DR</h3><p>This tutorial explains what a <em>service worker</em> is and how to use it. In JavaScript. There is a code example at the end of it. If you want to skip the reading, <a href="https://github.com/mihailgaberov/learn-service-workers">here</a> is the Git repo and <a href="https://compassionate-brahmagupta-71d9b4.netlify.com/">here</a> you may see a live demo.</p><h3>The Theory</h3><p>Let’s see first what a w<em>orker </em>is this 👀 and what s<em>ervice </em>can we use it for 🤓.</p><p>The<em> service worker</em> is a <a href="https://developers.google.com/web/fundamentals/primers/service-workers/">simple script</a>. JavaScript code, that your browser runs in the background, separate from a web page. It’s very convenient to use service workers for features that don’t need a web page or user interaction. One of the most common usages is intercepting and handling network requests. Which includes managing a cache of responses. The following is a simple example of how to include a service worker in your application run.</p><p>Usually, in the entry point of your app, you put this:</p><pre>if (&#39;serviceWorker&#39; in navigator) {<br>  window.addEventListener(&#39;load&#39;, function() {<br>    navigator.serviceWorker.register(&#39;/service-worker.js&#39;);<br>  });<br>}</pre><p>This way of using service workers is a little bit improved than the basic one. Which would be directly calling the <em>register</em>() method inside the <em>if statement. </em>In this case, we use the window load event to register the service worker after the page has finished loading. After doing this, you need to add your service worker code in <em>service-worker.js</em> file. At this point, you might want to take a look at mine service worker file here.</p><p><em>All major browsers support Service Workers now and you can start using them right away.</em></p><h3>The Example</h3><p>Enough theory, let’s build a real example app, that will leverage the service workers feature.</p><p>Let’s imagine we are building an app that needs to load a big chunk of data. It could be, for example, a nice, big full-screen image, we would display on the front page. Or it could be a big video clip we have to wait to load. This is an ideal use case for a service worker to shine. Let’s see how. 👀</p><p>In our specific case, we will use the clock time to show the benefit of using service workers. What I mean is, that we will build a simple app, showing the time. It will have a nice, big button for fetching a nice, big image. And it will provide the user with an option to choose <strong>to use or not </strong>a service worker.</p><p>Here is a screenshot of how it looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*2K-IvfpcK017rGsX1Hsm8w.png" /></figure><p>What this app demonstrates is, that when fetching the image (by clicking the button, wow!) with an active service worker — we don’t get blocked UI (user interface, i.e. fields, buttons, 🐛). If you choose not to use the service worker, you will get a frozen UI for a certain period of time. When the work completes and the main thread frees itself, it will unfreeze the UI.</p><p>If you don’t want to clone and run the code yourself, jump straight to the <a href="https://compassionate-brahmagupta-71d9b4.netlify.com/">live demo</a>.</p><h3>Conclusion</h3><p>This demo of service workers in action shows us the advantage we get from using them. Especially when you are trying to build responsive and robust JavaScript applications. No user wants to end up in a frozen page for an unknown time, as no developer should want that for his application’s users. Keeping in mind the above, service workers are a *must* now. And we should not neglect them.</p><p>🔥 Thanks for reading! 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e2ba71b90d6" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/optimize-your-javascript-app-by-using-service-workers-3e2ba71b90d6">Optimize your JavaScript app by using service workers</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a chat app with React, TypeScript and Socket.io]]></title>
            <link>https://medium.com/free-code-camp/build-a-chat-app-with-react-typescript-and-socket-io-d7e1192d288?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7e1192d288</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Fri, 26 Apr 2019 15:19:34 GMT</pubDate>
            <atom:updated>2019-04-30T15:16:57.390Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to build a chat app with React, TypeScript and Socket.io</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XB8rYOUoHDLtQHz470IDQw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Yhc7YGZlz3g?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Steve Halama</a> on <a href="https://unsplash.com/search/photos/coding-chat-application?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Originally published at </em><a href="https://mihail-gaberov.eu/how-i-build-chat-app-with-react-and-typescript-part1/"><em>mihail-gaberov.eu</em></a><em>.</em></p><p>This is going to be a thorough step-by-step guide for building a single page chat application using React, TypeScript and Socket.io.</p><p>If you want to skip the reading, <a href="https://github.com/mihailgaberov/chat">here</a> 💁 is the GitHub repository with a detailed <a href="https://github.com/mihailgaberov/chat/blob/master/README.md">README</a> 🙌, and <a href="https://mihails-chat.herokuapp.com/#/chat">here</a> you can check the live demo. 🎀 In order to play with it, you need to open it in two different browsers (or browser tabs) or devices (you may use your computer and your smartphone) and chat with each other.🎀</p><h3>Research</h3><p>When you are about to start a new project, it’s a good practice to do initial research about the technical stack you are planning to use.</p><p>In other words, you may want or need — especially if you don’t have prior experience with it — to investigate on each technology you will be using. I recommend doing that separately. Take one of the them and create a small app that you can play with.</p><p>If you need to check how the integration of two or more technologies is going to work in a real project — then you might want to include them all together in your “<em>research-test-play</em>” app — but preferably do your research one at a time.</p><h4>Getting to the point</h4><p>When I started thinking about making this <a href="http://mihails-chat.herokuapp.com/#/chat">chat application</a>, I did exactly what I described above. I haven’t had recent experience with <a href="http://www.typescriptlang.org/">TypeScript</a> and none with <a href="https://socket.io/">Socket.io</a>, so I had to take a look at those and get myself familiarized with what is their current state. As my plan was to use <a href="https://reactjs.org/">React</a> as a main UI library, I needed to see how it was going to work with the other guys in the equation. So I did.</p><p>I created two small applications (repos <a href="https://github.com/mihailgaberov/playing-with-socketio">here</a> and <a href="https://github.com/mihailgaberov/react-contextapi-with-typescript">here</a>) with these technologies, just to be able to play with them and learn how could I use them in my future chat application.</p><p>After my initial research was done I was able to start thinking and planning the implementation of my main chat app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QAQkM3QZvs8T6WPZqmtug.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/3TRdlKU-3II?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hutomo Abrianto</a> on <a href="https://unsplash.com/search/photos/research-done?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>High level planning</h3><p>Usually what people mean when they say “<em>high level plan” </em>is that they are looking for the <em>big picture</em>. Which means we need to create a rough plan of our execution and define our main pillars, but without going into too much detail. Now when we have clear idea of what to do, let’s start doing it! 👷</p><p><strong>Note:</strong> From this point forward I will be assuming that you are following my steps as I describe them, hence I will be writing in the second person.<em> </em>👨</p><h4>Tech stack</h4><p>We already mentioned the main technologies we will be using, but let’s define a proper list of all of them here:</p><ul><li><a href="https://github.com/Microsoft/TypeScript-React-Starter#create-our-new-project">React with TypeScript</a> (create-react-app my-app --scripts-version=react-scripts-ts) — a UI library we will use for building our application’s user interfaces.</li><li><a href="https://redux.js.org/">Redux</a> — a state management library we will use for managing our application’s state.</li><li><a href="https://expressjs.com/">Express.js</a> — Node.js web application framework we will use for creating an <a href="https://expressjs.com/en/starter/hello-world.html">http server</a> that we will need in our application, in order to take advantage of Socket.io engine.</li><li><a href="https://socket.io/">Socket.io</a> — a JavaScript library for real time web applications. It enables real time, bi-directional communication between web clients and servers. We will use it to implement a simple chat behavior in our app.</li><li><a href="https://www.styled-components.com/docs">styled-components</a> — a small library that we will be using for adding styles to our app and make the look and feel beautiful. It utilizes tagged template literals to style your components and removes the mapping between components and styles. This means that when you’re defining your styles, you’re actually creating a normal React component that has your styles attached to it.</li><li><a href="https://jestjs.io/">Jest</a>/<a href="https://airbnb.io/enzyme/">Enzyme</a> — a JavaScript Testing Framework and a JavaScript Testing Utility that we will be using to write unit tests for our application. Both have great integration into the React ecosystem and are heavily used in real projects.</li></ul><h4>Application Features</h4><p>In this section we will describe what the features of our application are going to be.</p><p>Every time when we plan a new project, we must define certain criteria which will describe some level of completion when met.</p><p>In other words, we need to set a limit point which, once reached, will show that our project is completed or at least in its first version. There is a famous saying, that could be matched to the issue with the “never ending” projects:</p><blockquote>“A good plan today is better than a perfect plan tomorrow.<strong>”</strong> — or we may say that a working project today is better than a perfect project tomorrow.</blockquote><p>Here is my list with the features I wanted to implement initially:</p><h4><strong>Header</strong></h4><ul><li>Chat tab — blinking when new message is received until it is read, or when the user is on Settings page</li><li>Settings tab</li><li>Unread messages counter</li><li>Font Awesome icons</li></ul><h4><strong>Chat page</strong></h4><ul><li>Chat area (includes left aligned and right aligned messages)</li><li>Message (text, datetime, left or right depending on if it’s received or sent)</li><li>Showing the nickname only of the sender</li><li>Message sender — input field and button. Input is cleared and focused when button is clicked</li><li>Send messages with CTRL+ENTER</li><li>Auto scroll to bottom when the chat area is not enough to show all messages</li></ul><h4><strong>Settings page</strong></h4><ul><li>UserProfile component — possibility to change user name</li><li>Interface color component — change the color theme of the app</li><li>ClockDisplay component — change the time mode 12h or 24h, shown with each message</li><li>Send messages with Ctrl+Enter — On/Off</li><li>LanguageSwitcher — drop down menu allowing changing the language of the app (currently English and Deutsch are supported)</li><li>Reset button — resets all settings stored to local storage</li></ul><p><strong>Improvements<br></strong>At the time of writing this, there are still some pending features I would like to implement. Below is the list of all improvements I did or plan to do in future (the ones with the thumb emoji are already implemented):</p><ul><li>Add video chat feature.</li><li>👍 Added AM/PM time formatting for when 12h mode is selected.</li><li>👍 Added possibility to send message via ENTER by default. If the setting to send messages with CTRL+ENTER is ON, then this is going to be the only way (except via mouse/touch of course).</li><li>👍 Optimized for iDevices (media queries).</li><li>👍 Fix blinking/active class for the Chat tab issue — related to React Router not able to properly re-render connected components <a href="https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md">https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md</a></li><li>👍 Clear input field when new message is sent.</li><li>👍 Auto scroll to bottom main chat area when new messages exceed available space.</li><li>👍 Prevent ‘doubling messages’ (or multiple messages duplicates when more clients are connected).</li><li>👍 Add unit tests for the react components.</li><li>Add unit tests for redux stuff — reducers, store, action creators.</li><li>👍 Add media queries for responsiveness — test and adjust on more devices.</li><li>👍 Add demo to Heroku.</li><li>👍 Add nice how-to in README.</li><li>Add animations for the messages.</li><li>Add sounds (with options to turn on/off in settings).</li><li>Add more color themes.</li><li>Add welcome message (broadcasts when a new user is connected).</li><li>👍 Add icons (use Font Awesome).</li><li>History of all the conversations.</li><li>Handle case when socket’s connection state change (visually).</li><li>Handle case when there has been a socket error.</li><li>Handle case when a very long word (without) spaces is entered and it goes beyond the message background color.</li><li>👍 Emoticons support — such as :D, :P, :), ;), 😉, ❤️, etc.</li><li>👍 Link Parser — Youtube link (embedded video should appear), link to an image (embedded image should appear), all other links should appear as anchor.</li></ul><p>When we know the initial plan and the requirements we need to fulfill, we can do our high level analyses. Our app will have two pages, Chat and Settings, accessible via tab controls.</p><p>The Chat page will contain the main chat area with the controls needed to send messages (input field and a button).</p><p>The Settings page will contain a few controls for selecting the options described above.</p><p>With that in mind we can go to the next section where we will create a more detailed plan before the actual implementation.</p><h3>More detailed planning</h3><p>In this section we need to have a deeper look at our application and define what will be the building blocks for it. Since we are going to use React and we know that in the React world the term <em>component </em>is widely used, we may refer to our building blocks as components. We will have components responsible for purely visual stuff, as well as such for managing the local storage, for example.</p><p>Let’s try to imagine mentally how our app will look in the end and what components it will need. What we already know is this:</p><h4><strong>Server part</strong></h4><p>We will need an HTTP server that will take care of starting the server and handling interactions with Socket.io (sending and receiving messages). Our server logic will be simple enough to live in only one file. You can see the actual implementation <a href="https://github.com/mihailgaberov/chat/blob/master/server/index.js">here</a>.</p><p><strong>Client part<br></strong>Here we need to have all the visual controls, plus means for managing interactions with local storage, where we will save the user preferences, as well as handling of the translations and color themes.</p><p>Now is a good moment to point out that for implementing the <a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/TranslationsProvider.tsx">translations and theming</a> functionality in the app, I have used <a href="https://reactjs.org/docs/context.html">React Context API</a>. Also, since I knew I would have to deal with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">Local Storage</a>, I did <a href="https://github.com/mihailgaberov/misc/tree/master/manage-local-storage-with-typescript">another round</a> of the “<em>research-test-play”</em> trip. And the output of it was that I already had a <a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/localStorageService.ts">nice service</a>, which provides all the functionalities I needed.</p><p>Another thing you will notice when looking at the <a href="https://github.com/mihailgaberov/chat/tree/master/src/components">components</a> folder is that every component has its own directory with a few files in it.</p><p>These files serve the following logic:</p><p><strong>index.ts</strong> → entry point, just expose the component itself. This helps for not having to write repeatedly and long import statements. Here is an example:</p><pre><em>// Instead of having to write this:<br></em>import ChatArea from &#39;../../ChatArea/ChatArea&#39;;</pre><pre>// We can have just this:<br>import ChatArea from &#39;../../ChatArea&#39;;</pre><p><strong>&lt;ComponentName&gt;.tsx</strong> (<a href="https://github.com/mihailgaberov/chat/blob/master/src/components/ChatArea/ChatArea.tsx">ChatArea.tsx</a>) → actual component implementation live here.</p><p><strong>&lt;ComponentName&gt;.test.tsx </strong>(ChatArea.test.tsx)<strong> → </strong>unit<strong> </strong>tests of the component live here.</p><p><strong>&lt;StyledComponentName&gt;.tsx </strong>(StyledChatArea.tsx) → CSS styles of the component live here.</p><p>The same pattern is used for most of the components, exception are only the <em>pages</em>, such as the components which play the role of parents for all the inner parts — <a href="https://github.com/mihailgaberov/chat/tree/master/src/components/pages/Chat">ChatPage</a> and <a href="https://github.com/mihailgaberov/chat/tree/master/src/components/pages/Settings">SettingsPage</a>.</p><p>So, with that said, I think we can see what would be our application structure when we try to “componentize” it. Here a list of the <a href="https://github.com/mihailgaberov/chat/tree/master/src/components">components</a> I came up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*NY35awws7ZOkh8etHOJkjw.png" /><figcaption>Chat application components</figcaption></figure><p><strong>Note:</strong> all names are a matter of personal choice, feel free to name yours as you wish.</p><p>Let me try to give you a bit more detailed explanation for each of them below:</p><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/AppRouter">AppRouter</a> — contains the main app routing logic. For instance, here we define the app routes by giving them the path and component to load when this path is reached. Uses <a href="https://reacttraining.com/react-router/web/guides/philosophy">React Router</a> package.</li><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/ChatArea">ChatArea</a> — represents the main chat area, where all the messages are being displayed. It’s responsible also for auto scrolling down when the visible area limit is reached.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*Sx6WIoqTnxRZ4YO3egA6BA.png" /><figcaption>ChatArea component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/ClockModeSelector">ClockModeSelector</a> — responsible for displaying controls allowing the user to select the time display mode -12h or 24h. It uses a common component called <a href="https://github.com/mihailgaberov/chat/tree/master/src/components/common/RadioGroup">RadioGroup</a> (will describe it below) and the Local Storage service to write/read from the browser’s local storage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*53qZzpKfO6ALW5So93X6dQ.png" /><figcaption>ClockModeSelector component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/common/RadioGroup">common/RadioGroup</a> — this is a common component, built with the idea to be re-usable all over the app. We use this component in a few other components, such as ClockModeSelector, <a href="https://github.com/mihailgaberov/chat/tree/master/src/components/ThemeSelector">ThemeSelector</a> and <a href="https://github.com/mihailgaberov/chat/tree/master/src/components/SendingOptions">SendingOptions</a>. It contains logic for displaying two radio buttons with the possibility to pass a callback function which will execute a certain action depending on your needs.</li><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/LanguageSelector">LanguageSelector </a>— responsible for displaying a select input control for choosing the app language. It accepts a function that is coming from the <a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/TranslationsProvider.tsx">TranslationsProvider</a> utility and does the actual language change.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*udPi2SgeogBN5QL_q23Hpg.png" /><figcaption>LanguageSelector component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/Message">Message </a>— this component is responsible for displaying each chat message, sent or received. It includes the nickname of the sender and timestamp showing the time when the message was sent/received. It also provides support for emojis (like ❤️) and links parsing — see the screenshot below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*GtM3k_EoB2Iq-Wya5p_s2g.png" /><figcaption>Message component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/MessageSender">MessageSender </a>— this is the component that provides the necessary user interface controls for sending messages — a text input field and a Send button. It contains logic for defining the different ways of sending — via click or key press (with ENTER or CTRL+ENTER), as well as clearing the input field when a new message is sent.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*XogXNNyuyEGNeg6JzKlktg.png" /><figcaption>MessageSender component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/Navigation">Navigation </a>— here lives the implementation of the app navigation. It consists of two tabs — <strong>Chat </strong>and <strong>Settings </strong>and contains logic for connecting to sockets, by sending a R<a href="https://redux.js.org/basics/actions">edux action</a> when the component is mounted. It manages an <a href="https://github.com/mihailgaberov/chat/tree/master/src/components/UnreadMessagesCounter">UnreadMessagesCounter </a>component by passing it the count of the currently unread messages (this happens when the user receives a message while being on the Settings page). It also has a logic responsible for making the tab blink when a new message arrives.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*Nl2-3zJvidqV8DG4j4dddQ.png" /><figcaption>Navigation component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/blob/master/src/components/Nickname/">Nickname </a>— this is simple component for rendering the nickname of a chat user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*IXnA_J1kUyMCY3lc40vK0Q.png" /><figcaption>Nickname component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/ResetButton">ResetButton </a>— this will be a simple component, used in the <strong>Settings </strong>page for rendering a Reset button. The function is going to be exactly that — resetting the settings selections that are already saved into the local storage, if any.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*47R5gBNjjBThsC_SYWfYlA.png" /><figcaption>ResetButton component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/SendingOptions">SendingOptions </a>— responsible for displaying options for choosing if a message can be sent via CTRL+ENTER. It works same way as ClockModeSelector component — uses RadioGroup component and accepts a callback function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*bxAP64H75j0BuMzrpGAaow.png" /><figcaption>SendingOptions component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/ThemeSelector">ThemeSelector </a>— same as the component above. The only difference is that here the user is allowed to select a color theme. In our case the options are only two — light theme or dark theme.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*Fm-vlKR0ROEBsNnOKhgieA.png" /><figcaption>ThemeSelector component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/Timestamp">Timestamp </a>— simple component used for rendering the time of the messages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*5Ppt70G2iG69HNCHj0HMZA.png" /><figcaption>Timestamp component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/UnreadMessagesCounter">UnreadMessagesCounter </a>— this is the component I mentioned a little bit earlier. It shows a counter indicating the number of the received, but not yet read, messages. It’s positioned in the navigation area.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*jZecIylkAB0s1h-Z4bjKAA.png" /><figcaption>UnreadMessagesCounter component</figcaption></figure><ul><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/UserProfile">UserProfile </a>— this the component responsible for rendering an input field the user can use for changing its user name. It’s saving the new user name into the local storage, using a <a href="https://lodash.com/docs/4.17.11#debounce">debounce</a> function. This means that the actual triggering of the function is happening some defined time after the user stops typing. It also triggers another Redux action, so we can use the new username in our Redux state.</li><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/pages/Chat">pages/ChatPage</a> — parent component that encloses everything shown on the Chat page.</li><li><a href="https://github.com/mihailgaberov/chat/tree/master/src/components/pages/Settings">pages/SettingsPage</a> — parent component that encloses everything shown on the Settings page.</li></ul><p>Everything described above was related to our React components. All of them are responsible for getting some data and displaying it in a proper way. In order to be able to handle this data in a convenient for us way, we use a few more things. Let’s have a look at these things in the sections below.</p><h3>Redux State Management</h3><p>Here we will talk about how our app state is being managed by using Redux and socket middleware.</p><h4>Store</h4><p>Our <a href="https://github.com/mihailgaberov/chat/blob/master/src/store/index.ts">store</a> is going to be relatively simple. We will have only two reducers defining a piece of the state reserved for the socket state and for the messages state. This is also where we apply our middleware. If you are familiar with <a href="https://redux-saga.js.org/">Redux Saga</a> package, you have probably seen this pattern of applying custom middleware when using Redux.</p><p>Something like this:</p><pre>import { createStore, applyMiddleware } from &#39;redux&#39;<br>import createSagaMiddleware from &#39;redux-saga&#39;</pre><pre>import reducer from &#39;./reducers&#39;<br>import mySaga from &#39;./sagas&#39;</pre><pre>// create the saga middleware<br>const sagaMiddleware = createSagaMiddleware()<br>// mount it on the Store<br>const store = createStore(<br>  reducer,<br>  applyMiddleware(sagaMiddleware)<br>)</pre><p>But in our case it would be like this:</p><pre>import { createStore, combineReducers, applyMiddleware, compose } from &#39;redux&#39;;<br>import socketReducer from &#39;./socket/reducer&#39;;<br>import messageReducer from &#39;./message/reducer&#39;;<br><strong>import socketMiddleware from &#39;./socket/middleware&#39;;</strong></pre><pre>const rootReducer = combineReducers({<br>  socketState: socketReducer,<br>  messageState: messageReducer<br>});</pre><pre>// @ts-ignore<br>const composeEnhancers = <em>window</em>.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;</pre><pre>const index = {<br>  ...createStore(rootReducer, composeEnhancers(<strong>applyMiddleware(socketMiddleware)</strong>))<br>};</pre><pre>export default index;</pre><h4>Message</h4><p>After defining our store, it’s time to see how are we going to handle the messaging in Redux. We have defined our actions <a href="https://github.com/mihailgaberov/chat/blob/master/src/store/message/actions/index.ts">here</a> and our messageReducer <a href="https://github.com/mihailgaberov/chat/blob/master/src/store/message/reducer/index.ts">here</a>.</p><ul><li><strong>Actions </strong>— here we define the main actions needed for sending and receiving messages, as well as changing the user name.</li><li><strong>Reducer </strong>— here is where our messageReducer function lives and where we define what happens when one of the actions above is dispatched.</li></ul><h4>Socket</h4><p>We follow the same logic as above here. We have our <a href="https://github.com/mihailgaberov/chat/blob/master/src/store/socket/actions/index.ts">socket actions</a>, the <a href="https://github.com/mihailgaberov/chat/tree/master/src/store/socket/middleware">middleware </a>I mentioned above, and the <a href="https://github.com/mihailgaberov/chat/blob/master/src/store/socket/reducer/index.ts">socketReducer</a>.</p><ul><li><strong>Actions </strong>— contains actions for connecting the socket (the one dispatched from the Navigation component in the beginning when the application is started) and one for when the connection status is changed, i.e. showing if we are connected or not.</li><li><strong>Middleware </strong>— contains implementation of a simple socket middleware, which provides us with the minimum functionality we need in our chat app.</li><li><strong>Reducer </strong>— here is where our socketReducer function lives and where we define what happens when one of the actions above is dispatched.</li></ul><h3>Theming</h3><p>In order to implement the possibility for setting different color themes in our application and considering the fact we are using styled-components, I used a <a href="https://www.styled-components.com/docs/advanced">ThemeProvider </a>— component provided by them. <a href="https://github.com/mihailgaberov/chat/blob/master/src/theme/index.ts">Here</a> is the implementation that includes defining objects with custom colors used in the themes.</p><p>The logic behind applying the selected color theme resides <a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/TranslationsProvider.tsx">here</a>. Ideally the containing component should be named something different than <em>TranslationsProvider, </em>as it doesn’t handle only the translations, as we see. We could add this to the list of future improvements/refactoring.</p><p>Here is how the existing color themes look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*tooJRolBzH403D6jMQUVLg.png" /></figure><h3>Utilities</h3><p>In almost every software project, at certain point, the need of common reusable functions emerges. This is the moment when developers usually create a common shared file or files, containing such helpers functions. In our case this would be <strong>/utilities</strong><em> </em>folder that currently contains four files. I will go through each of them below and explain the logic behind my decision to create it and put it there:</p><ul><li><a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/common.ts">common.ts </a>— here is the place where I decide to put such common helper functions, which are supposed to be easily used where needed in the whole application. In this specific case you will find four functions used for time formatting, and a helper for defining the active page and for scrolling an element to bottom.</li><li><a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/localStorageService.ts">localStorageService.ts</a> — I have already mention this service in the first part of this tutorial. Here is where all methods for manipulating the local storage live.</li><li><a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/TranslationsProvider.tsx">TranslationsProvider.tsx</a> — this component was also mentioned multiple times, but for the sake of clarity I will mention it again here. It contains the logic for providing translations and color theme in the app.</li><li><a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/withTranslations.tsx">withTranslations.tsx </a>— this is a <a href="https://tylermcginnis.com/react-higher-order-components/">higher-order component (HOC)</a> which is responsible for attaching the application context (containing the translations and themes themselves) to any component being wrapped by it.</li></ul><p>Here is an example of how is it used:</p><pre>export default withTranslations(SettingsPage as React.FunctionComponent);</pre><p>We have walked a long way to here and we still haven’t started with the actual implementation.</p><p>That is a vivid pointer for us to show how important and extensive the planning phase of a project could be.</p><p>Let’s jump now to the implementation phase in the next section.</p><h3>Implementation</h3><p>If you reached this point of the tutorial, you should have a very clear idea of what are we going to build. Here, we are about to find out how are we going to do it.</p><h4>Starting small</h4><p>As with any other project we should strive to start with small, incremental chunks and build on them. In our case I have decided to start first with building the header navigation. The reason for that was that I wanted to have the router and the navigation controls in place, so I could easily navigate through the tabs while developing and testing.</p><h4>Settings page</h4><p>After I had finished with the header and navigation parts, I decided to jump to the settings page first. Again, my reasoning was very simple — I wanted to build first what I was going to use in the Chat page. In other words I wanted to be able to customize my chat area, messages, ways of sending and so on, before implementing them.</p><p>So I started building component by component as I described them in the previous section. Once I had the full Settings page finished, I was able to go and start implementing the Chat page components. But before that, I had to take care of the supporting stuff — integrating with <a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/localStorageService.ts">local storage</a> and adding <a href="https://github.com/mihailgaberov/chat/blob/master/src/utilities/TranslationsProvider.tsx">translations mechanism</a>.</p><h4>Chat page</h4><p>After I have done all from above, the implementation of the Chat page and its components was fairly easy. I had to take care of the visual part manly and make the integration with the Redux store. As you <a href="https://github.com/mihailgaberov/chat/blob/master/src/components/pages/Chat/ChatPage.tsx">already saw</a>, I had to implement only two components which are shown and used on the Chat page — ChatArea and MessageSender.</p><h3>Adding improvements</h3><p>I want to say a few words here regarding the app improvements we did or will do in the future. Usually when we have a new requirement (let’s call it “requirement”, that makes is sound closer to what would be in a real project), it is again a very good idea to do some initial research, instead of jumping directly into implementation. You will be surprised how many solutions are already out there, waiting for us to use them.</p><p>In other words, we don’t have to invent the wheel again.</p><p>This is what I did when I started thinking about adding support for emoticons or link parsing. It turned out that there are already solutions I could use with a little tweaking from my side, just to make them fit well in my project.</p><p>Here are the links to the packages I used:</p><ul><li><a href="https://www.npmjs.com/package/linkifyjs">https://www.npmjs.com/package/linkifyjs</a></li><li><a href="https://docs.microlink.io/sdk/getting-started/react/">https://docs.microlink.io/sdk/getting-started/react/</a></li><li><a href="https://www.npmjs.com/package/react-emojione">https://www.npmjs.com/package/react-emojione</a></li><li><a href="https://www.npmjs.com/package/get-urls">https://www.npmjs.com/package/get-urls</a></li></ul><p>And <a href="https://github.com/mihailgaberov/chat/blob/master/src/components/Message/Message.tsx">here</a> you can see how I used them in our chat app.</p><h3>Deploying to Heroku</h3><p>I have written <a href="https://mihail-gaberov.eu/creating-twitter-bot/">another article</a> in the past. It was about totally different subject, but there is a part exactly related to how to deploy an app to Heroku. You might find it useful to check it out.</p><p>For deploying our chat application to <a href="https://herokuapp.com/">Heroku</a>, I will assume you have already an account and can easily follow the steps below:</p><ol><li>npm build to build the project to build folder.</li><li>Add build folder to Git to make sure it will be committed.</li><li>Make sure that express server loads static resources from it.</li><li>Commit all: git commit -m &#39;Deploy to Heroky&#39;.</li><li>Run git push heroku master.</li><li>Open the app from the given URL (in my case: <a href="https://mihails-chat.herokuapp.com/#/chat">mihails-chat.herokuapp.com</a>).</li></ol><h3>Future (possible) plans</h3><p>At the time of writing this I was thinking it might be very interesting to try building the same application with the other super famous UI library on the market — <a href="https://angular.io/">Angular</a>. I still think it will be worth it, but I am not sure whether I will have the time and the power to do it 😐.</p><p>In any case, what I am thinking about it as a pure, technical comparison of two major UI libraries from the developer’s point of view.</p><p>If I do it, I will make sure you know it!</p><p>🔥 Thanks for reading! 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7e1192d288" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/build-a-chat-app-with-react-typescript-and-socket-io-d7e1192d288">Build a chat app with React, TypeScript and Socket.io</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to solve the Sherlock and Anagrams coding challenge in JavaScript]]></title>
            <link>https://medium.com/free-code-camp/how-to-solve-the-sherlock-and-anagrams-coding-challenge-in-javascript-a80baa908637?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a80baa908637</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding-challenge]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Tue, 23 Apr 2019 15:28:07 GMT</pubDate>
            <atom:updated>2019-04-23T15:28:07.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_R6N6YK1HylRbzIi_0KPw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/qYfwGVNJqSA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Javier Quesada</a> on <a href="https://unsplash.com/search/photos/task-anagrams?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Originally published at </em><a href="https://mihail-gaberov.eu/sherlock-and-anagrams/"><em>mihail-gaberov.eu</em></a><em>.</em></p><p>This post is going to get you through my solution to a coding challenge called “Sherlock and Anagrams.” You may take a look at it in <a href="https://www.hackerrank.com/challenges/sherlock-and-anagrams">HackerRank</a>.</p><p>I spent a lot of time trying to solve it, with JavaScript. When I tried to google it, I could not find a decent JS solution. I found just one, and it was not working correctly. Also, any explanations were completely out of the question. That’s why I decided to write an article about it and try to put some nice and easy to digest explanations along the way. Keep reading now!</p><p>⚠️CAUTION: <em>I will roll out my solution below with short explanations about each of the steps. If you want to give a try yourself, please stop here and go to HackerRank’s site.</em></p><h3>Problem</h3><p>Two strings are <a href="http://en.wikipedia.org/wiki/Anagram">anagrams</a> of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.</p><p>For example <em>s = mom</em>, the list of all anagrammatic pairs is [<em>m, m</em>], [<em>mo, om</em>] at positions [[0], [2]], [[0, 1], [1, 2]] respectively.</p><p><strong>Constraints<br></strong>Length of the input string: 2 ≤ |s| ≤ 100<br>String <em>s</em> contains only lowercase letters from the range ascii[a-z].</p><h3>Analysis</h3><p>First thing first — we need to get a better understanding of the whole problem. What is an anagram? What is an anagrammatic pair? Can I see one? Also, what exactly does it mean <em>substrings</em>?</p><p><strong>In other words, we need to have a clear picture of what are we trying to solve, before solving it.</strong></p><p>From the description of the problem, we can deduct all we need. Keep walking! 🚶</p><p><em>I think this is a good moment to mention that the challenge in question is under the “Dictionaries and Hashmaps” section in the HackerRank website. You’ll probably think that you should use this kind of data structure when solving it.</em> 😇</p><h4>Anagrams</h4><p>Since we are going to look for anagrams, let’s start with them. As it is described above, an anagram of one word is another word that has the same length and is created with the same characters from the former word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*zx2ysHYqabizusSXZkVL0Q.gif" /><figcaption>Animation for the anagram “Listen = Silent”</figcaption></figure><p>So we will have to look for words and compare them with other words, in order to see if they are anagrammatic pairs. Once found, we will just count them.</p><h4>Anagrammatic pairs</h4><p>Since we’ve seen what an anagram is, it should be relatively easy to conclude that an anagrammatic pair is just two strings that are anagrams. Such as “mo” and “om”, or “listen” and “silent”. We will have to count how many pairs like this can be found in a given string. In order to do that, we need to split this original string to substrings.</p><h4>Substrings</h4><p>Substrings, as the name infers, are parts of a string. These parts could be just a letter or a pair of letters, such as what have we seen in the example above — “<em>m</em>” or “<em>mo.</em>” In our solution, we will split the original string to such substrings and then we will go over them and do the comparison, which will tell us whether we have anagrammatic pairs among them.</p><h3>Solution</h3><p>Now that we’ve done our analysis, it’s showtime! 🎆</p><p>Let’s summarize:</p><ol><li>We need to find all substrings of the given string — create a method for that.</li><li>We need to be able to check if two strings are anagrams — create a method for that.</li><li>We need to count all anagrammatic pairs in the given string — create a method for that.</li><li>Combine everything from above and spit the result — create a method for that.</li></ol><h4>Get all substrings</h4><p>This will be our helper method for finding all substrings of a given string:</p><pre>function getAllSubstrings(str) {<br>  let i, j, result = [];<br><br>  for (i = 0; i &lt; str.length; i++) {<br>    for (j = i + 1; j &lt; str.length + 1; j++) {<br>      result.push(str.slice(i, j))<br>    }<br>  }<br>  return result<br>}</pre><p>As you can see, it has O(n²) time complexity. For our case, it does the job, because we have limited length of the input string (up to 100 characters).</p><h4>Check for anagrams</h4><p>This will be our helper method for checking if two strings are anagrammatic pairs:</p><pre>function isAnagram(str1, str2) {<br>  const hist = {}<br><br>  for (let i = 0; i &lt; str1.length; i++) {<br>    const char = str1[i]<br>    if (hist[char]) {<br>      hist[char]++<br>    } else {<br>      hist[char] = 1<br>    }<br>  }<br><br>  for (let j = 0; j &lt; str2.length; j++) {<br>    const char = str2[j]<br>    if (hist[char]) {<br>      hist[char]--<br>    } else {<br>      return false<br>    }<br>  }<br><br>  return true<br>}</pre><p>Remember that we assumed we’d most probably have to use data structures such as hashmaps or dictionaries (given the section where this challenge is found on HackerRank).</p><p>We use a simple JavaScript object to play the role of a hashmap. We do two iterations — one per string. When we iterate over the first one, we add its characters as keys to the hashmap and count their appearances, which are going to be stored as their values. Then we do another iteration over the second string. Check if its characters are stored in our hashmap. If yes — decrement their value. If there are missing characters, which means the two strings are not an anagrammatic pair, we simply return false. If both loops complete, we return true, signifying that the strings being analyzed are an anagrammatic pair.</p><h4>Do the counting</h4><p>This is the method, where we will use the helper for checking if a pair is anagrammatic and count it. We do that with the help of JavaScript arrays and the methods they provide. We iterate over an array containing all the substrings of the original string. Then we get the correct element and remove it from the array. And then we do another loop through that array and return 1 if we find that there is an anagram of the current element. If nothing is found, we return 0.</p><pre>function countAnagrams(currentIndex, arr) {<br>  const currentElement = arr[currentIndex]<br>  const arrRest = arr.slice(currentIndex + 1)<br>  let counter = 0<br><br>  for (let i = 0; i &lt; arrRest.length; i++) {<br>    if (currentElement.length === arrRest[i].length &amp;&amp; isAnagram(currentElement, arrRest[i])) {<br>      counter++<br>    }<br>  }<br><br> return counter<br>}</pre><h4>And in the end</h4><p>The only thing left to be done now is to combine all of the above and spit the desired result. Here is how the final method looks like:</p><pre>function sherlockAndAnagrams(s) {<br>  const duplicatesCount = s.split(&#39;&#39;).filter((v, i) =&gt; s.indexOf(v) !== i).length<br><br>  if (!duplicatesCount) return 0<br>  let anagramsCount = 0<br><br>  const arr = getAllSubstrings(s)<br><br>  for (let i = 0; i &lt; arr.length; i++) {<br>    anagramsCount += countAnagrams(i, arr)<br>  }<br><br>  return anagramsCount<br>}</pre><p><em>Maybe you have noticed, here I am checking first for duplicates in order to know if I should continue further. As if there are no duplicated letters, then it’s not possible to have an anagram.</em></p><p>And finally, we get all substrings into an array, iterate over it, count the anagrammatic pairs that are found and return this number.</p><p>You can find the full code <a href="https://github.com/mihailgaberov/misc/blob/master/coding-challenges/sherlock-and-anagrams.js">here</a>.</p><h3>Conclusion</h3><p>These kind of exercises are very good for making you think algorithmically. Also they change your way of working in your day to day job. My recommendation would be to do the same I am trying to do — train your brain now and then with one of those. And if you can — share. I know sometimes you don’t have time for such challenges, but when you do — go for it.</p><p>My personal feeling after finishing this was total satisfaction, which is completely understandable, considering the time it took me to do it. But in the end, dear reader, I am even happier I can share this experience with you😌!</p><p>🔥 Thanks for reading! 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a80baa908637" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-solve-the-sherlock-and-anagrams-coding-challenge-in-javascript-a80baa908637">How to solve the Sherlock and Anagrams coding challenge in JavaScript</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to optimize your JavaScript apps using Loops]]></title>
            <link>https://medium.com/free-code-camp/how-to-optimize-your-javascript-apps-using-loops-d5eade9ba89f?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5eade9ba89f</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 16:57:20 GMT</pubDate>
            <atom:updated>2019-04-15T16:57:20.958Z</atom:updated>
            <content:encoded><![CDATA[<p>Everyone wants high-performance apps — so in this post, we’ll learn how to achieve that goal.</p><p><em>Originally published at </em><a href="https://mihail-gaberov.eu/optimizing-javascript-apps-loops/"><em>mihail-gaberov.eu</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTVOyrPN6uiYJKCVmuBxtQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/7NtiJBowheE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Zachary Young</a> on <a href="https://unsplash.com/search/photos/loops?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>One of the easiest and most neglected things you can do to boost the performance of your JavaScript applications is to learn how to write properly high performing loop statements. The idea of this article is to help with that.</p><blockquote><em>We will see the main types of loop used in JavaScript and how can we write them in a performant way.</em></blockquote><p>Let’s begin!</p><h3>Loop performance</h3><p>When it comes to loop performance, the debate is always about which loop to use. Which is the fastest and most performant? The truth is that, of the four loop types provided by JavaScript, only one of them is significantly slower than the others — for-in loop. <em>The choice of loop type should be based on your requirements rather than performance concerns</em>.</p><p>There are two main factors that contribute to loop performance — <strong>work done per iteration</strong> and <strong>number of iterations</strong>.</p><p>In the sections below we will see how, by decreasing them, we can have a positive overall impact on loop performance.</p><h3>For Loop</h3><p>ECMA-262 (the specification that defines JavaScript’s basic syntax and behaviour), the third edition, defines four types of loops. The first is the standard for loop, which shares its syntax with other C-like languages:</p><pre>for (var i = 0; i &lt; 10; i++){<br>    //loop body<br>}</pre><p>This is probably the most commonly used JavaScript looping construct. To understand how can we optimize its work, we need to dissect it a little bit.</p><h4>Dissection</h4><p>The for loop consists of four parts: initialization, pretest condition, loop body, and post-execute. The way it works is the following: first, the initialization code is executed (var i = 0;). Then the pretest condition (i &lt; 10;). If the pretest condition evaluates to true, then the body of the loop is executed. After that the post-execute code (i++) is run.</p><h4>Optimizations</h4><p>The first step in optimizing the amount of work in a loop is to minimize the number of object members and array item lookups.</p><p>You can also increase the performance of loops by reversing their order. In JavaScript, reversing a loop does result in a small performance improvement for loops, provided that you eliminate extra operations as a result.</p><p>Both of the statements above are valid for the other two faster loops as well (while and do-while).</p><pre>// original loop<br>for (var i = 0; i &lt; items.length; i++){<br>    process(items[i]);<br>}</pre><pre>// minimizing property lookups<br><strong>for (var i = 0, len = items.length; i &lt; len; i++){</strong><br>    process(items[i]);<br>}</pre><pre>// minimizing property lookups and reversing<br><strong>for (var i = items.length; i--; ){</strong><br>    process(items[i]);<br>}</pre><h3>While Loop</h3><p>The second type of loop is the while loop. This is a simple pretest loop, consisting of a pretest condition and a loop body.</p><pre>var i = 0;<br>while(i &lt; 10){<br>    //loop body<br>    i++;<br>}</pre><h4>Dissection</h4><p>If the pretest condition evaluates to true, the loop body is executed. If not — it’s skipped. Every while loop can be replaced with for and vice versa.</p><h4>Optimizations</h4><pre>// original loop<br>var j = 0;<br>while (j &lt; items.length){<br>    process(items[j++]);<br>}</pre><pre>// minimizing property lookups<br>var j = 0,<br><strong>    count = items.length;</strong><br><strong>while (j &lt; count){</strong><br>    process(items[j++]);<br>}</pre><pre>// minimizing property lookups and reversing<br><strong>var j = items.length;</strong><br><strong>while (j--){</strong><br>    process(items[j]);<br>}</pre><h4>Do-While Loop</h4><p>do-while is the third type of loop and it’s the only post-test loop in JavaScript. It is comprised of body loop and post-test condition:</p><pre>var i = 0;<br>do {<br>    //loop body<br>} while (i++ &lt; 10);</pre><h4>Dissection</h4><p>In this type of loop, the loop body is executed always at least once. Then the post-test condition is being evaluated, and if it’s true, another loop cycle is executed.</p><h4>Optimizations</h4><pre>// original loop<br>var k = 0;<br>do {<br>    process(items[k++]);<br>} while (k &lt; items.length);</pre><pre>// minimizing property lookups<br>var k = 0,<br><strong>    num = items.length;</strong><br>do {<br>    process(items[k++]);<br><strong>} while (k &lt; num);</strong></pre><pre>// minimizing property lookups and reversing<br><strong>var k = items.length - 1;</strong><br>do {<br>    process(items[k]);<br><strong>} while (k--);</strong></pre><h3>For-In Loop</h3><p>The fourth and the last type of loop is called for-in loop.<strong> </strong>It has a very special purpose —<strong> enumerates the named properties of any JavaScript object.</strong> Here it is how it looks:</p><pre>for (var prop in object){<br>    //loop body<br>}</pre><h4>Dissection</h4><p>It’s similar to the <em>regular </em>for loop only by its name. The way it works is totally different. And this difference makes it much slower than the other three loops, which have equivalent performance characteristics such that it’s not useful to try to determine which is fastest.</p><p>Each time the loop is executed, the variable prop has the name of another property, which is a <em>string</em>, on the object. It will execute until all properties have been returned. These would be the properties of the object itself, as well as the ones inherited through its prototype chain.</p><h4><strong>Notes</strong></h4><p><strong>You should never use “</strong><strong>for-in” to iterate over members of an array</strong>.</p><p>Each iteration through this loop causes a property lookup either on the instance or on the prototype, which makes the for-in loop much slower than the other loops. For the same number of iterations, it could be seven-time slower than the rest.</p><h3>Conclusion</h3><ul><li>The for, while, and do-while loops all have similar performance characteristics, and so no one loop type is significantly faster or slower than the others.</li><li>Avoid the for-in loop unless you need to iterate over a number of unknown object properties.</li><li>The best ways to improve loop performance are to <strong>decrease the amount of work done per iteration and decrease the number of loop iterations</strong>.</li></ul><p>I hope this was useful for you, as it was for me!</p><p>🔥 Thanks for reading! 🔥</p><h3>Resources</h3><p>“<a href="https://www.amazon.com/High-Performance-JavaScript-Application-Interfaces/dp/059680279X">High Performance JavaScript</a>” — Nicholas C. Zakas</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5eade9ba89f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-optimize-your-javascript-apps-using-loops-d5eade9ba89f">How to optimize your JavaScript apps using Loops</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks: Revisited]]></title>
            <link>https://medium.com/hackernoon/react-hooks-revisited-322d6020ce9c?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/322d6020ce9c</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Fri, 22 Mar 2019 17:23:39 GMT</pubDate>
            <atom:updated>2019-05-17T05:31:58.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revisiting React Hooks</h3><p><em>Originally published at </em><a href="https://mihail-gaberov.eu/react-hooks-revisited"><em>mihail-gaberov.eu</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BveNxR6PettAS98SNHAlQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Xh6BpT-1tXo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Etienne Girardet</a> on <a href="https://unsplash.com/search/photos/hooks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Intro</h3><p>Some time ago, before ↪️ <a href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a> ↩️ ️️were officially released, I have written <a href="https://mihail-gaberov.eu/react-hooks-a-new-way-of-working-with-react-state/">another article</a> about them. It was an attempt to learn and explain this new feature. Now, when they are officially part of the last React <a href="https://github.com/facebook/react/blob/master/CHANGELOG.md#1680-february-6-2019">releases</a>, I have decided to revisit them and try to present better examples of their usage.</p><h3>Why</h3><p>Right after my first <a href="https://mihailgaberov.github.io/react-hooks/#0">presentation</a>, I’ve received some very useful comments by a colleague of mine. Comments regarding the presentation and the examples, and advice of how I can do better. I kept these comments in my email for some time. And today I will try to follow them, so we can get better understanding about this feature, which now can be used in any new or existing project.</p><h3>Show Time</h3><p>Since we have covered the theory behind the hooks <a href="https://mihail-gaberov.eu/react-hooks-a-new-way-of-working-with-react-state/">last time</a> (and there are a lot of nice explanations on the subject out there now), I don’t plan to repeat it here. What I plan is to start directly with examples, but to strive to keep them as clear and focused as possible. 🐽</p><h4>Example 1:</h4><p>In this example we will take a closer look at the two of <strong>the most important built-in hooks — useState and useEffect.</strong></p><p>📌 <strong>State Hook — useState()</strong></p><p>📚 Theory — this is just to remind us what is this hook meant to be used for and then we will see how to use it below. What <a href="https://reactjs.org/docs/hooks-state.html">React documentation</a> say is: “ <strong><em>one of the Hooks provided by React is called </em></strong><strong><em>useState. We’re also sometimes going to refer to it as the “State Hook”. It lets us add local state to React function components</em></strong>”. This means that whenever we need to manipulate our component state, we can go for <strong><em>useState</em></strong> hook.</p><p>👉 Practice — you can see <a href="https://codesandbox.io/s/9y96vvwwq4">live example here and play with it</a>.</p><p><strong>📌 Effect Hook — useEffect()</strong></p><p>📚 Theory — this is just to remind us what is this hook meant to be used for and then we will see how to use it below. What <a href="https://hackernoon.com/tagged/react">React</a> documentation say is: “ <strong><em>The Effect Hook lets you perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects</em></strong>”. This means that whenever we need to perform some side effect or use a result returned from such, we should go for <strong>useEffect</strong> hook.</p><p>Here is an example in which we will see what are the differences when we use this hook with <strong>one</strong> <strong>parameter and with two parameters</strong>. We also will see what happens if we provide a <strong>return value for the first param</strong>.</p><p>👉 Practice — you can see <a href="https://codesandbox.io/s/9y96vvwwq4">live example here and play with it</a>.</p><p><em>If you want to go really deeper into this, here Dan Abramov posted </em><a href="https://overreacted.io/a-complete-guide-to-useeffect/"><em>A Complete Guide to useEffect</em></a><em>. It’s a really long article, but it’s worth it.</em></p><h3>Example 2</h3><p>In this example we will take a closer look at the <strong>custom hooks</strong> and how can we use one.</p><p><strong>📌 Custom Hook (e.g. usePictures)</strong></p><p>📚 Theory<strong> → </strong>as we remember from the <a href="https://mihail-gaberov.eu/react-hooks-a-new-way-of-working-with-react-state/">last time</a>, custom hooks are exactly what the name implies. Hooks that we can create by our own and we can use built-in hooks in them. <em>Or simply said — our own functions that can benefit from React built-in hooks.</em> In the example below, we will see how to create such and use it in combination with previously mentioned hooks. For instance, how can we fetch a 3rd party REST API and do something with the result. 💻</p><p>👉 Practice — you can see <a href="https://hooks-revisited.herokuapp.com/">live example here</a> and the code for it <a href="https://github.com/mihailgaberov/react-hooks/blob/hooks-revisited/src/App.js">here</a>.</p><h3>Conclusion</h3><p>In the end of this brief retrospection, we could refresh our memories by mentioning some of the key things we need to keep in mind, when using React Hooks.</p><p><strong>Hooks don’t remove classes — we still can use classes if we want or need them.</strong></p><p><strong>Hooks rules — we must follow them when using hooks:</strong></p><p>☙ <a href="https://reactjs.org/docs/hooks-rules.html#explanation">Only Call Hooks at the Top Level </a>— this basically means that we must not call hooks (yes, remember, hooks are functions and we can call them) inside loops, conditions and nested functions. And we must follow the order in which Hooks are called. <strong>Note that you don’t need to worry about this problem if you use the </strong><a href="https://www.npmjs.com/package/eslint-plugin-react-hooks"><strong>provided lint rule</strong></a><strong>.</strong></p><p>☙ <a href="https://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions">Only Call Hooks from React Functions</a> — this means we are not suppose to call Hooks from regular <a href="https://hackernoon.com/tagged/javascript">JavaScript</a> functions. Instead, we should be calling them only from React function components or custom Hooks.</p><p><em>I hope this article helps you feel more confident when using React Hooks. </em>😏</p><p>🔥 Thanks for reading! 🔥</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=322d6020ce9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/react-hooks-revisited-322d6020ce9c">React Hooks: Revisited</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React hooks: a new way of working with React state]]></title>
            <link>https://medium.com/free-code-camp/hooking-with-react-hooks-964df4b23960?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/964df4b23960</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Thu, 08 Nov 2018 15:54:15 GMT</pubDate>
            <atom:updated>2019-02-06T17:08:21.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNln2JsoPZEVzgGPJhs98w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/gTQbZXL417Q?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brook Anderson</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>Updated: With React 16.8, </strong><a href="https://reactjs.org/docs/hooks-intro.html"><strong>React Hooks</strong></a><strong> are available in a stable release!</strong></p><p>Outdated: Hooks are still an experimental proposal. They’re currently in React v16.7.0-alpha</p><p><strong>TL;DR <br></strong>In this article we will attempt to understand what are <a href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a> and how to use them for our good. We will implement different examples and see the differences (gains) Hooks bring to us. If you want to skip the reading, <a href="https://mihailgaberov.github.io/react-hooks/">here</a> you can find shorter version in a few slides. And <a href="https://github.com/mihailgaberov/react-hooks">here</a> 🎁 you may get the examples and try them yourself.</p><h3>What are <em>React Hooks</em>?</h3><blockquote>Simple functions for hooking into the React state and lifecycle features from function components.</blockquote><p>What this means is that hooks allow us to easily manipulate our function component’s state without needing to convert them into class components. This saves us from having to deal with all the boilerplate code involved.</p><p>Hooks don’t work inside classes — they let you use React without classes. And also, by using them, we can totally avoid using lifecycle methods, such as <em>componentDidMount</em>, <em>componentDidUpdate</em>, etc. Instead, we will use built-in hooks like <em>useEffect</em>, <em>useMutationEffect</em> or <em>useLayoutEffect</em>. We will see how in a moment.</p><p>Hooks are JavaScript functions, but they impose two additional <a href="https://reactjs.org/docs/hooks-rules.html">rules</a>:</p><p>❗️ Only call Hooks <strong>at the top level</strong>. Don’t call Hooks inside loops, conditions, or nested functions.</p><p>❗️ Only call Hooks <strong>from React function components</strong>. Don’t call Hooks from regular JavaScript functions. There is just one other valid place to call Hooks — your own custom Hooks. We’ll see them later in this article.</p><h3>Why are they <em>good thing?</em></h3><p>😟 <strong>Reusing logic</strong><br>Up until now, if we wanted to reuse some logic in React, we had two options: <a href="https://tylermcginnis.com/react-higher-order-components/">higher-order components</a> or <a href="https://www.robinwieruch.de/react-render-props-pattern/">render props</a>. With React Hooks we have an alternative, that comes with a much easier to understand (in my personal opinion!) syntax and logic flow.</p><p>😟 <strong>Giant components</strong><br>By avoiding the boilerplate code we need to write when using classes or by removing the need for multiple nesting levels (which could come when using render props), React Hooks solve the issue of having giants components (that are really hard to maintain and debug).</p><p>😟 <strong>Confusing classes</strong><br>Again, allowing us NOT to use classes or class components in our applications makes the developers’s (especially beginner’s) life easier. This is because we don’t have to use the ‘this’ keyword and we don’t need to have the understanding of how bindings and scopes work in React (and JavaScript).</p><p>This is NOT to say that we (the developers) don’t have to learn these concepts — on the contrary we must be aware of them. But in this case, when using React hooks, our worries are one fewer 😏.</p><blockquote><strong><em>So, after pointing out what issues the hooks solve, when would we use them?</em></strong></blockquote><blockquote><em>If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We’re going to do that in the next examples.</em></blockquote><h3>How to use <em>React Hooks</em>?</h3><p>React Hooks come to us as <a href="https://reactjs.org/docs/hooks-overview.html">built-in ones</a> and <a href="https://reactjs.org/docs/hooks-custom.html">custom ones</a>. The later are the ones we can use for sharing logic across multiple React components.</p><p>As we’ve already learned, hooks are simple JavaScript functions, which means we will be writing just that, but in the context of React <em>function</em> components. Previously these components were called <em>stateless</em>, a term that is not valid anymore, as <em>hooks</em> give us a way to use the state in such components 🙌.</p><blockquote><em>An important thing to remember is that we can use both built-in and custom hooks multiple times in our components. We just have to follow the </em><a href="https://reactjs.org/docs/hooks-rules.html"><em>rules of hooks</em></a><em>.</em></blockquote><p>The following examples try to illustrate that.</p><h4>Basic built-in hooks</h4><ul><li><a href="https://github.com/mihailgaberov/react-hooks/blob/master/src/components/Counter/CounterHooked.js">useState</a> hook — returns a stateful value and a function to update it.</li><li><a href="https://reactjs.org/docs/hooks-effect.html">useEffect</a> hook — accepts a function that contains imperative, possibly effectful code (for example fetching data or subscribing to a service). This hook could return a function that is being executed every time before the effect runs and when the component is unmounted — to clean up from the last run.</li><li><a href="https://github.com/mihailgaberov/react-hooks/blob/master/src/components/Counter/CounterHooked.js">useContext</a> hook — accepts a <a href="https://reactjs.org/docs/context.html">context</a> object and returns the current <a href="https://github.com/mihailgaberov/react-hooks/blob/master/src/ColorContext.js">context</a> value, as given by the nearest context provider for the given context.</li></ul><h4>Custom hooks</h4><p><strong>A custom Hook is a JavaScript function whose name starts with “</strong><strong>use” and that may call other Hooks.</strong> For example, <a href="https://github.com/mihailgaberov/react-hooks/blob/master/src/useFriendName.jshttps://github.com/mihailgaberov/react-hooks/blob/master/src/useFriendName.js">useFriendName</a> below is our first custom Hook:</p><pre>export default <em>function</em> useFriendName(<em>friendName</em>) {</pre><pre><em>  const</em> [isPresent, setIsPresent] = useState(false);<br>  <br>  useEffect(() <em>=&gt;</em> {<br>    <em>const</em> data = MockedApi.fetchData();<br>    data.then((<em>res</em>) <em>=&gt;</em> {<br>      res.forEach((<em>e</em>) <em>=&gt;</em> {<br>        if (e.name === friendName) {<br>          setIsPresent(true);<br>        }<br>     });<br>    });<br>  });</pre><pre>  return isPresent;<br>}</pre><p>Building your own custom hooks lets you extract component logic into reusable functions. This could be your application’s shared functionality that you can import everywhere you need it. And also, we must not forget, that our custom hooks are the other allowed (<a href="https://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions">see the rules</a>) places to call built-in hooks.</p><h3>Conclusion</h3><p>React Hooks are not really a new feature that popped out just now. They are another (better ❓) way of doing React components that need to have <em>state </em>and/or<em> lifecycle </em>methods. Actually, they use the same internal logic that is being used currently by the class components. To use them or not — this is the question to which the future will give the best answer.</p><blockquote><em>My personal opinion? That this is going to be the future of any React development that involves state and lifecycle usage.</em></blockquote><p>Let’s see how the community will react to the proposal 📓 and hopefully we will see them polished and fully functioning in the next React releases. 🍀</p><p>🔥 Thanks for reading! 🔥</p><h3>References</h3><p>Here you may find the links to the resources I found useful when writing this article:</p><ul><li><a href="https://github.com/mihailgaberov/react-hooks">https://github.com/mihailgaberov/react-hooks</a>/ — link to GitHub repo with the examples and presentation.</li><li><a href="https://mihailgaberov.github.io/react-hooks/#0">https://mihailgaberov.github.io/react-hooks/</a> — link to presentation slides.</li><li><a href="https://reactjs.org/docs/hooks-intro.html">https://reactjs.org/docs/hooks-intro.html</a> — official ReactJS blog.</li><li><a href="https://youtu.be/dpw9EHDh2bM">https://youtu.be/dpw9EHDh2bM</a> — Introduction to Hooks, React Conf 2018</li><li><a href="https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889">https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889</a> — An explanatory article by Dan Abramov.</li><li><a href="https://daveceddia.com/useeffect-hook-examples/">https://daveceddia.com/useeffect-hook-examples/</a> — A very useful article explaining different use cases of useEffect hook.</li><li><a href="https://ppxnl191zx.codesandbox.io/">https://ppxnl191zx.codesandbox.io/</a> — An example of a React animation library experimenting with Hooks.</li><li><a href="https://dev.to/oieduardorabelo/react-hooks-how-to-create-and-update-contextprovider-1f68">https://dev.to/oieduardorabelo/react-hooks-how-to-create-and-update-contextprovider-1f68</a> — A nice and short article showing how to create and update context provider with React Hooks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964df4b23960" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/hooking-with-react-hooks-964df4b23960">React hooks: a new way of working with React state</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What should we test (ReactJS Components)]]></title>
            <link>https://medium.com/hackernoon/what-should-we-test-reactjs-components-647ded674928?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/647ded674928</guid>
            <category><![CDATA[presentations]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Thu, 12 Jul 2018 07:34:51 GMT</pubDate>
            <atom:updated>2019-05-17T05:31:59.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyxuq21keffc5b0d_lMkUw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ZMraoOybTLQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Artem Sapegin</a> on <a href="https://unsplash.com/search/photos/unit-testing-reactjs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There are a lot of discussions in the web when we talk about testing. And even more about unit testing. In <a href="https://reactjs.org/">React</a>.</p><p><strong>TL;DR<br></strong>This is going to be a brief summary of what and how should we think about when we test a <a href="https://github.com/facebook/react/">ReactJS</a> application. More specific, what should we write tests for, when creating React components for our app. If you want to skip the reading, <a href="http://mihailgaberov.github.io/testing-reactjs-presentation/">here</a> you can find shorter version in a few slides.</p><blockquote>All of the points below are recommended by people smarter than me. I just collected them as a summary of best practices, trying to help my team to decide on the matter. And start using them in our day-to-day work.</blockquote><h4>Do we need unit tests?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*2e88BniCmTaqAFldMVbQ2Q.png" /></figure><p>This is a long time discussion, that has only one right answer. Yes! Tests provide developers with confidence. This confidence allows us to produce <a href="https://hackernoon.com/tagged/software">software</a> with better quality. To do proper refactoring. And to reason better about what we do.</p><p>In short term it might look it’s not worth it. That it takes too much time. Time we might spend for implementing features instead. But very soon after the start of every project, the payoff of having a nice test suit is huge. The punishment of not having such, especially when a release date is <a href="https://hackernoon.com/tagged/approaching">approaching</a> — disaster!</p><h4>Test render logic</h4><p>When we write tests for our components, we write them in such way that they test only the render logic and don’t care about any internal implementation. What does this mean? It means that, your test should be testing the things that the user will be seeing and interacting with. Let’s say you are testing a component that displays a button on the screen.</p><blockquote>When the user clicks the button, your component renders a message in a <em>div</em> element. Your test should check practically for the same — check if the button is clickable and if this <em>div</em> exists after the clicking.</blockquote><h4>No lifecycle methods</h4><p>Tests should not test lifecycle methods, they are supposed to be covered by React itself. If we have some logic that needs to be tested in these methods, we should try to extract it in another testable place and only use it in there. Ideally, in our <em>componentDidMount </em>method for example, we should have only functionality for fetching data (calling an API for example). All the rest that you might be tempted to leave there, should be extracted in other methods, that could be tested, if needed.</p><h4>No outsiders</h4><blockquote>(Unit) Tests should not test interaction with outside world!</blockquote><p>The name “unit” implies independence and autonomy. A unit test should be an encapsulated piece of code, that has inside everything it needs to perform its job. When we need to write tests which need data, we use mocks. That said, every interaction with APIs, DBs, etc., is not a matter of unit tests and should not be tested in such.</p><h4>Small, smaller, easier</h4><p>Tests should be small and easy to read — if we need to test a big component with a lot of dependencies, we need to consider splitting it to smaller testable pieces.</p><blockquote>Dīvide et imperā.</blockquote><p>As the famous quote above implies, it’s a lot more easier to deal with small, well modularized components, than the opposite. Also, if we need to use big mocks, we need to extract them out of the test and only use them by importing, in order to avoid polluting the test file.</p><h4>Example</h4><ul><li>Given a simple component containing a button and a text field</li><li>We should test what the user sees — rendering, and what the user can do — user interaction</li><li>If there is visual change after clicking — test for it</li><li>If there is a value returned after clicking — test for it</li></ul><p><em>But we don’t care about the internal implementation of the click handler!</em></p><p>I have prepared a small example, trying to demonstrate the above. You can find it <a href="https://github.com/mihailgaberov/testing-reactjs-examples">here</a>. In order to run it locally on your machines, just clone it and install the dependencies. Then do ‘<em>npm run test</em>’. 🚀 📜</p><h4>References</h4><p>There are many resources on that subject online, but I am going to list here the ones I have found very useful and learned from them.</p><p>👏 <a href="https://medium.freecodecamp.org/the-right-way-to-test-react-components-548a4736ab22">A nice article</a> on the subject</p><p>👏 <a href="https://www.leighhalliday.com/testing-react-jest-enzyme-sinon">Another good one</a> for testing with Jest, Enzyme and Sinon</p><p>👏 <a href="https://github.com/sapegin/jest-cheat-sheet">Jest Cheat sheet</a></p><p>👏 <a href="https://mihailgaberov.github.io/testing-reactjs-presentation">Presentation slides</a> online</p><p>👏 <a href="https://github.com/mihailgaberov/testing-reactjs-examples">Github repo</a> with working examples</p><h4>Conclusion</h4><p>The important lesson we must keep from all this testing stuff is, that no matter how exactly we write our tests (well it matters…a bit 💬), as long as we write tests at all. This way of thinking and working should become our second nature when we are striving to produce errorproof software. With time and practice the things become better and easier. The most important thing for us is to never stop improving.</p><blockquote>Keep going!</blockquote><p>🔥 Thanks for reading! 🔥</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=647ded674928" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/what-should-we-test-reactjs-components-647ded674928">What should we test (ReactJS Components)</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve your Twitter bot with MongoDB]]></title>
            <link>https://itnext.io/improve-your-twitter-bot-with-mongodb-1f1e51e632d4?source=rss-73c3949b96a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1e51e632d4</guid>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Мihail Gaberov]]></dc:creator>
            <pubDate>Wed, 30 May 2018 06:08:04 GMT</pubDate>
            <atom:updated>2018-05-31T08:09:03.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9KQSsKKYfqFv33_iNWsBg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/RGwhPC5tLMQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mihai Varga</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/@mihailgaberov/creating-a-twitter-bot-in-5am-2a42a9920e67">another article</a> we saw how to create a twitter bot that sends private messages to his followers, containing tweets searched by predefined criteria — certain hashtags selected by us. This time we will improve the reports being sent, by adding additional functionality. We will store the results in a database and filter the newly received tweets according to what we have stored. Thus, we will be able to send only (<em>almost*</em>) unique results.</p><p><strong>TL;DR<br></strong>This is the second part of a <a href="https://medium.com/@mihailgaberov/creating-a-twitter-bot-in-5am-2a42a9920e67">step by step tutorial</a> showing you how to create your own Twitter bot and host it on <a href="http://herokuapp.com/">heroku</a>. This time we will upgrade our code by using <a href="https://www.npmjs.com/package/mongoose">mongoose </a>and <a href="https://www.mongodb.com/">MongoDB</a> to produce better results. Also, we will extend the usage of our <em>helpers,</em> by extracting there the composing of the messages content. In the end, we will see how can we use <a href="https://mlab.com/">Mlab</a> hosting service (free plan) to host our database there.</p><p>If you want to skip right to the code, here is <a href="https://github.com/mihailgaberov/twitter-bot/tree/v2">the GitHub repo</a>.</p><p><strong>Reasoning<br></strong>What is the reason to do that?</p><blockquote>Right now there are plenty of tutorials and articles about creating twitter bots out there, but I could not find any of them that extends the subject to the next level — offering direction for improving the way your bot handles the data.</blockquote><p>That is why I decided to introduce a new player in the equation. Something that will help us to do more with our tweet reports — database.</p><p><strong>Database<br></strong>MongoDB is a famous <a href="https://en.wikipedia.org/wiki/NoSQL">NoSQL </a>database that has great integration with <a href="https://nodejs.org/en/">Node.js</a>. It’s quick and easy to use, and it’s perfect for our purpose. We will use it to eliminate the duplicates from our feed, before sending the messages to the followers.</p><h4>Step by step</h4><p>If you want to follow through, here are the steps you may take:</p><ol><li>Register a new account in <a href="https://mlab.com/signup/">Mlab</a>.</li><li>Add your DB_USER and DB_PASSWORD credentials to your .env file (same way as we did in the <a href="https://medium.com/@mihailgaberov/creating-a-twitter-bot-in-5am-2a42a9920e67">first part</a> with the Twitter API keys).</li><li>Create a new directory called “/<em>db</em>” in the root folder of your project and add a new file in it: <strong>db.js</strong><em>. </em>Here is where we will put the logic for connecting with the database.</li><li>At the beginning of the file, import <a href="http://mongoosejs.com/">mongoose</a> — a <a href="https://www.mongodb.org/">MongoDB</a> object modeling tool, designed to work in an asynchronous environment. We will see a bit later how easy is to work with MongoDB when using <strong>mongoose</strong> and <strong>Node.js</strong>.</li></ol><pre>const mongoose = require(&#39;mongoose&#39;)</pre><p>5. Next step is to compose our connection string. We need this, in order to be able to connect and consume our database. Here is how it should look like:</p><pre>const dbURI = `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@ds219130.mlab.com:19130/twitter-bot-db`</pre><p>6. The rest of this <a href="https://github.com/mihailgaberov/twitter-bot/blob/v2/db/db.js">file</a> is just simple logic coming from <em>mongoose,</em> related to setting up different listeners for different events that might occur. One of these events is “<em>connected</em>”, this tells us when we are successfully connected to our database.</p><p>7. Setup your database model — in the same folder create a new file called <strong>tweets.model.js</strong>. Here is the logic behind our database model. A simple <a href="http://mongoosejs.com/docs/guide.html">mongoose schema</a> that serves as a blueprint for our database documents. It contains only four fields. The unique ID parameter called i<em>d_str.</em> We will use that when checking for duplicates. The content (s<em>tatus)</em> of the tweet, the a<em>uthor </em>name and the creation date of a tweet —<em> created_at</em>. All of the fields are defined as <a href="http://mongoosejs.com/docs/schematypes.html"><em>string and</em> <em>required</em></a><em>.</em></p><pre>const tweetSchema = new Schema({ <br>  id_str: { <br>    type: String, <br>    unique: true,<br>    required: true <br>  }, <br>  status: { <br>    type: String, <br>    required: true <br>  }, <br>  author: {<br>    type: String,<br>    required: true <br>  }<br>  created_at: {<br>    type: String,<br>    required: true<br>})</pre><p>8. The last step, for getting our database up and running, is to create our database controller. This file will contain the main logic for interacting with the database. Here we will put methods for reading and writing records from and into it. Also here, we will implement the functionality for getting only the unique tweets from each feed and record them for post usage. In order to start, create a new file in the “<em>/db</em>” folder, name it <strong>tweets.controller.js </strong>and paste <a href="https://github.com/mihailgaberov/twitter-bot/blob/v2/db/tweets.controller.js">this code</a> in it. You probably have seen already, that in this file we have some of the methods exported and some of them defined as local constants. Following the best practices, we will be using only the exported ones in our main flow.</p><blockquote>By defining the rest as local, we limit unnecessary exposure to the outer world.</blockquote><p>Local methods, used only here:</p><pre>const fetchTweets = function () { ... }<br>const recordTweet = function ({ id_str, text, user }) {...}</pre><p>Exported methods, used in <a href="https://github.com/mihailgaberov/twitter-bot/blob/v2/bot.js"><em>bot.js</em></a>:</p><pre>module.exports.recordUniqueTweets = function (tweets) {...} module.exports.getUniqueTweets = function (latestTweets) {...}</pre><p><strong>Helpers<br></strong>In my <a href="https://medium.com/@mihailgaberov/creating-a-twitter-bot-in-5am-2a42a9920e67">previous article</a> I mentioned how good is to extract or modularize functionality that can be reused in many other places. We did that with a method for getting the current time. This time we will add another method to <a href="https://github.com/mihailgaberov/twitter-bot/blob/v2/helpers.js"><strong>helpers.js</strong></a><strong>, </strong>that we will be using for generating the messages content. If, for any reason, we don’t get any new tweets, we will send a message to the followers. Like this one:</p><pre><em>`-— Nothing new this time (14.05.2018 14.02).`.</em></pre><p>Also, we are going to refactor a little bit the method for getting the current time. And then we will be able to use it, when composing the messages content, to add the date of when a tweet is created.</p><pre>const from = this.getTime(tweet.created_at)</pre><p><strong>Updating main flow<br></strong>After we finish with the database related tasks, it’s time to amend our <a href="https://github.com/mihailgaberov/twitter-bot/blob/v2/bot.js">main application flow</a> and make it start using the new setup. Actually, the change we need to do is really minor. We need to import <strong>db.js</strong> and <strong>tweets.controller.js</strong> files from “<em>/db</em>” folder like so:</p><pre>require(&#39;./db/db&#39;)<br>const db = require(&#39;./db/tweets.controller&#39;)</pre><p>And then, in the callback of the first call that fetches the tweets, replace the <em>forEach </em>loop with the following:</p><pre>   db.getUniqueTweets(data.statuses).then((tweets) =&gt; {        <br>     const content = helpers.composeContent(tweets)<br>     db.recordUniqueTweets(tweets)<br>  ...<br>})</pre><p>That’s all. 👌</p><p>You can find the final version of the code <a href="https://github.com/mihailgaberov/twitter-bot/blob/v2/bot.js">here</a>.</p><p><strong>Hosting on Mlab<br></strong>OK, now we are done with the coding and it’s time to publish our updated application and the database it uses. To do so, we are going to use <a href="https://mlab.com/welcome/">Mlab</a> for the database and, again, <a href="http://herokuapp.com/home">Herokuapp</a> for the application itself.</p><p>If you need help for deploying the application with Heroku, you may take a look at the <a href="https://medium.com/@mihailgaberov/creating-a-twitter-bot-in-5am-2a42a9920e67">first part</a> of this tutorial. Just don’t forget to add the new config variables to “Config Vars” section, under “Settings” tab.</p><p>In order to start using your database hosted on Mlab, you first need to login into your account and create a new database, using the control panel provided there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71PlZ2K2UfzHUjNYfsWGfg.png" /></figure><p>Once created, just go to its settings and find the connection string that you need to add to your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMMLs0FnIJtIBSlD07NvQw.png" /></figure><blockquote>If you have followed the coding part of this tutorial, you will have to add a collection into the database and name it ‘tweets’, in order to stay aligned with the code and get a working application in the end.</blockquote><p>Once the database is properly created, the connection string is in place in your code and the application is deployed via Heroku, <strong>you are good to go! 🎆 🆒</strong></p><p><strong>Conclusion<br></strong>This article serves two purposes. One is to be like a logical continuation of the first <a href="https://medium.com/@mihailgaberov/creating-a-twitter-bot-in-5am-2a42a9920e67">article</a>. Second is to show how easily we can use noSQL database, like MongoDB, with Node.js, and services, like Mlab and Heroku, to achieve an improved version of a simple Twitter bot application. It might worth mentioning, that this way we actually are creating our own database with twitter statuses, that later might be used for something else. Maybe some statistical research or material for machine learning, who knows. <strong>The best part of this is, that everything is happening automatically</strong>.</p><blockquote>There will be always options. We just need to think about them.</blockquote><p>Note: <em>If you don’t want to use the user interface provided by Mlab, for interaction with the database, you can use other tools, such as </em><a href="https://studio3t.com/"><em>studio3t</em></a><em>.</em></p><p>Of course, any comments or questions are welcome.</p><p><strong>🔥 Happy coding! 🔥</strong></p><p><em>You can find my implementation here </em><a href="https://github.com/mihailgaberov/twitter-bot/tree/v2"><em>https://github.com/mihailgaberov/twitter-bot</em></a><em>. If you want to start receiving the same reports as me, follow my bot in Twitter @HerrKlinkerhof3.</em></p><p><em>I am saying ‘almost’, because, in some cases, you might get tweets with the same content, but posted by different accounts. According to the implemented check these are different as they have different IDs, but still…</em></p><p>Oh… and <strong>thank you</strong> for reading. 😅</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1e51e632d4" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/improve-your-twitter-bot-with-mongodb-1f1e51e632d4">Improve your Twitter bot with MongoDB</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>