<?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 Attila Oláh on Medium]]></title>
        <description><![CDATA[Stories by Attila Oláh on Medium]]></description>
        <link>https://medium.com/@attila.olah?source=rss-d0abf1129dba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*K-f04FRVqYMmlBL6.</url>
            <title>Stories by Attila Oláh on Medium</title>
            <link>https://medium.com/@attila.olah?source=rss-d0abf1129dba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 04:26:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@attila.olah/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[Unleashing the potential of AI for teaching drones: making advanced technologies accessible to all]]></title>
            <link>https://medium.com/supercharges-mobile-product-guide/unleashing-the-potential-of-ai-for-teaching-drones-making-advanced-technologies-accessible-to-all-a75afa7240f7?source=rss-d0abf1129dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a75afa7240f7</guid>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[drones]]></category>
            <category><![CDATA[javascript-face-api]]></category>
            <dc:creator><![CDATA[Attila Oláh]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 10:33:11 GMT</pubDate>
            <atom:updated>2023-02-09T10:33:11.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1gXnd6ZGNO0fpoEDf44OQ.png" /></figure><p>Have you ever wanted to tinker with artificial intelligence but felt intimidated by the math and technical aspects? Look no further! In this article, I’ll share my journey of using AI to tame a drone, all while avoiding the complex mathematics. Follow along as I demonstrate how it’s possible to utilize online resources to achieve impressive results with AI and drones.</p><p>In order to keep up with the pace of technology, we at <a href="https://supercharge.io/">Supercharge</a> put extra effort into researching hot topics such as AI and IoT. Our teams get to experiment with AI and IoT-related technologies to get familiar with these future-proof topics. I decided to do so myself too.</p><h3>What did my little experiment look like in the end?</h3><p>Let‘s rewind a few steps. A friend of mine gave me a helping hand around the house and also brought his new toy, a DJI Mavic drone. I was obsessed with the shipped features: following objects, face recognition and all the AI-driven camera techniques.</p><p>At the same time (in 2019), our tech teams were being trained in AI technologies by a specialist through multiple half-a-day-long sessions. With these recent experiences in my mind, I decided to make my own face-following drone. I also set up a few criteria to make it even more challenging:</p><ul><li>I do web frontend development on a daily basis, so I want to write <strong>JS only</strong>. No python this time. (Rapid prototyping AI-related app without Python seems to be stretching, but it is actually doable, you’ll see!)</li><li>I don’t want to understand the AI behind only to use <strong>AI as a service</strong></li><li>On top of everything, I aim to <strong>finish within 4 hours</strong></li></ul><p>Since I had a 4-hour time cap for delivery, I needed to be prepared for any potential issues and wrong tracks. To do this, I conducted a quick research and found the following sources to be very useful:</p><ul><li><a href="https://wesbos.com/drone-javascript">https://wesbos.com/drone-javascript</a></li><li><a href="https://github.com/dnomak/drone-keyboard/">https://github.com/dnomak/drone-keyboard/</a></li><li><a href="https://github.com/SovGVD/nodetello/">https://github.com/SovGVD/nodetello/</a></li><li><a href="https://www.youtube.com/watch?v=4KiH3Fq3olM">https://www.youtube.com/watch?v=4KiH3Fq3olM</a></li><li><a href="https://www.youtube.com/watch?v=esw88_gKOpA">https://www.youtube.com/watch?v=esw88_gKOpA</a></li><li><a href="https://terra-1-g.djicdn.com/2d4dce68897a46b19fc717f3576b7c6a/Tello%20%E7%BC%96%E7%A8%8B%E7%9B%B8%E5%85%B3/For%20Tello/Tello%20SDK%20Documentation%20EN_1.3_1122.pdf">DJI Tello SDK</a></li></ul><p>TLDR; By following the docs and videos above, I understood how to control the drone over WiFi using JavaScript and how to obtain the video stream from it. I found this to be the most critical part, but the community had already solved it, so it was my turn to build upon their work!</p><p>So, after I spent a couple of hours researching (I haven’t done any code at this point), I put my plan together using a <a href="https://store.dji.com/shop/tello-series">DJI Tello</a> drone:</p><ul><li>First of all, I need to establish a connection between the drone and my mac and take over the <strong>control of the drone</strong> (takeoff, move around on all axes, land)</li><li>Then somehow, fire up a JS based <strong>face recognition</strong> using my <em>webcam</em> first</li><li>In order to <strong>track the face position,</strong> I have to calculate the distance vectors on all three axes (how far the face is from the centre of the camera picture)</li><li>Replace the webcam video source with the <strong>drone’s camera</strong></li><li><strong>Control the drone</strong> programmatically using the distance vectors <strong>to follow the face</strong></li></ul><p>Let’s have a look at each step! I’ll post the corresponding changes from my <a href="https://github.com/hunhavoc/drone-ai-demo">Github repo</a>.</p><h4>Connecting to and controlling the drone</h4><p>First, I tried to use <a href="https://github.com/wesbos/javascript-drones">Wes Bos’ code</a> as a start. It soon turned out that I would need finer control over the drone than Wes’ code provides if I wanted smooth operations. Therefore, I switched to the more complex <a href="https://github.com/SovGVD/nodetello/">nodetello library</a>. If you compare the two codebases, you’ll find that Wes Bos’ code uses the basic movement commands (up, down, left, right, forward, back which are very limited in terms of precision — 20 cm is the smallest step it can take), and nodetello uses the completely different so-called rc a b c d command instead (referred to as stick in the code). Technical details can be found in the <a href="https://terra-1-g.djicdn.com/2d4dce68897a46b19fc717f3576b7c6a/Tello%20%E7%BC%96%E7%A8%8B%E7%9B%B8%E5%85%B3/For%20Tello/Tello%20SDK%20Documentation%20EN_1.3_1122.pdf">SDK documentation</a>. Okay, but what is the RC command? I assumed it to be the same as used by the official DJI Tello mobile app, where you have fine control over the drone using two sticks on the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXeiPTOy5AeBVMnwf00VAQ.jpeg" /><figcaption>Interface of the official Tello app. Can you see those “analogue” sticks? Source: <a href="http://tellohq.com/official-dji-ryze-tello-app/">http://tellohq.com/official-dji-ryze-tello-app/</a></figcaption></figure><p>So I copied both the server and client code of nodetello into my project and threw out the functions I didn’t need in my short-living project. In the end, I had a setup where I could connect to the drone over WiFi; I was able to control it like in a video game and also had a video stream in my browser. However, I didn’t investigate the camera part at this point — that is a couple of steps forward.</p><p><strong>With </strong><a href="https://github.com/hunhavoc/drone-ai-demo/commit/63b8734854302d840d3bea2798d3e925580ec01a"><strong>this</strong></a><strong>, we have Step#1 DONE.</strong></p><p><em>Disclaimer: I recommend </em><a href="https://www.youtube.com/watch?v=JzFvGf7Ywkk"><em>Wes Bos’ video tutorial</em></a><em> for educational purposes. He has done a very good job on demonstrating how any JS developer can make that drone fly.</em></p><h4>Fire up face recognition on webcam</h4><p>Based on our AI training, Python would be the most convenient ecosystem for rapid prototyping AI problems. My Google searches proved the same: lots of open source libraries, supporting community and tons of answered questions around. Python is also better performing than JS based solutions. But I stuck to my decision to use JS as I’m not experienced enough in Python to solve this puzzle under such time pressure.</p><p>I found <a href="https://github.com/justadudewhohacks/face-api.js/">face-api.js</a> to be the best solution for me. The library is built upon Google’s <a href="https://github.com/tensorflow/tfjs">tensorflow.js</a>, therefore, runs offline (which turned out to be a must because Tello sits on the WiFi during flights -&gt; there’s no internet connection on my Mac while the drone flies). Face-api.js provides both node.js and browser-based solutions, and I decided to have it done in the browser for my experimental project, considering that:</p><ul><li>I can easily get the webcam working in the browser using &lt;video&gt; tag</li><li>nodetello provides videostream on the client side out of the box</li><li>there would be less visual aid during development if I chose server side</li></ul><p>Before we continue, let’s have a look at the face-api.js features on <a href="https://justadudewhohacks.github.io/face-api.js/webcam_face_tracking">face-api.js playground</a>. I decided to use the Tiny Face Detector detector because I was convinced by the performance (high FPS) — detection confidence ratio. As it turned out later, its precision is way more unreliable when using the Tello’s camera than my webcam, so I switched to the more resource-heavy but also more reliable SSD Mobilenet V1 model.</p><p><strong>See coding progress </strong><a href="https://github.com/hunhavoc/drone-ai-demo/compare/63b8734854302d840d3bea2798d3e925580ec01a...cbda5bc004a05af703ef0c14455087b1efa75434"><strong>here</strong></a><strong>.</strong></p><h4>Math</h4><p>Face-api.js provides rich API, so it was really easy to extract the information I wanted: the bounding box of the detected face. It enabled me to draw a rectangle over the camera picture. What did I need it for? Not only that it looks super high-tech, it also acts as preventive logging. It helped me to debug and understand my own code further down the road.</p><p>Once I obtained the bounding box for my face in the camera frame, I had all the information I needed to calculate the distance of my face from the center of the frame. By finding the center of the bounding box, it was easy to determine the correction needed to move the face to the center of the video. This allowed me to use that information to make the drone follow faces. Calculating the distance on the X and Y axes is straightforward (this is the distance between the center of the bounding box and the center of the camera frame), but there is no information on the Z axis (the distance from the camera to the face) provided by face-api.js. I used the size of the bounding box to roughly estimate the distance between the camera and the face. I won’t go into the specifics of the calculations here, as <a href="https://youtu.be/esw88_gKOpA?t=283">Jabrils</a> has already covered them in detail.</p><p><a href="https://github.com/hunhavoc/drone-ai-demo/compare/8fd7a75e6c7aab288fe76ef0c22659d9fa3e63b2...47170a82db806e5b57667da908ab41bd6e11d593"><strong>Now</strong></a><strong> I had the numbers that told me how far the face was!</strong></p><h4>Use the drone’s camera instead of the webcam</h4><p>As I mentioned earlier, I already had a camera stream provided by nodetello. All I had to do was replace face-api’s webcamera video input with the canvas that holds the drone camera frames.</p><pre>const droneCamCanvasEl = document.querySelector(&quot;#videoFeed canvas:not(#draw)&quot;);<br>const detection = await faceapi.detectSingleFace(useWebcam ? videoEl : droneCamCanvasEl);</pre><p>Github link <a href="https://github.com/hunhavoc/drone-ai-demo/compare/47170a82db806e5b57667da908ab41bd6e11d593...5365f7b89cec6f9f3c2149f3facf6e66751418c7">here</a>.</p><h4>Putting everything together</h4><p>Let’s summarise what I achieved already:</p><ul><li>the ability to control the drone using a keyboard</li><li>face recognition on the drone’s camera frame</li><li>numbers indicating the distance of the face from the center of the camera on each axis</li></ul><p>The final step is to use this information to tell the drone which direction to move in order to keep the face centered. This is the fun part!</p><p>Before I tell you how I managed to make it kind of work, let’s learn flight terminology! We need to understand what throttle, pitch, roll and yaw are.</p><ul><li><em>Throttle</em>: controls the elevation. All four rotors are running at the same speed.</li><li><em>Pitch</em>: forward/backward movement similar to a car. When pitching, two of the rotors in the back or front are running at a higher speed to move the drone forward or backward.</li><li><em>Roll</em>: moving to the sides. When the left rotors are running at a higher speed, the drone moves to the right side, and vice-versa in the opposite direction.</li><li><em>Yaw</em>: rotating around the vertical middle axis. When the left-spinning rotors run at a higher speed, the drone turns to the left. The same goes for the other side.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrVU9EjPdpAdNOBxOAIsSQ.png" /><figcaption>Terminus technicus of flight</figcaption></figure><p>Let’s start with the easiest parameter: throttle. When the face is above the center of the image, I need to increase the throttle. When it is below, I need to decrease it.</p><p>A primitive first implementation looks like this:</p><pre>function controlThrottle(relativeDistanceVector) {<br>  const direction =<br>    relativeDistanceVector[1] &gt; 0 ? -1 : relativeDistanceVector[1] &lt; 0 ? 1 : 0;<br>  return direction;<br>}<br>const stickData = { pitch: 0, roll: 0, throttle: 0, yaw: 0 };<br>stickData.throttle = controlThrottle(relativeDistanceVector);<br>sendCmd(&quot;stick&quot;, stickData);</pre><p>The above snippet declares a stickData object that feeds the cmd command of the Tello SDK. Default values are 0, so the drone won’t move if stickData stays intact. Knowing the distance vector of the detected face, I can calculate the desired movement direction on the vertical axis. While this code is theoretically correct, it will not work well in practice. The main issue is that the drone will never reach the perfect position, so the calculated correction needed will always be a non-zero value. This means that the drone will constantly go up and down, trying to reach the zero position, but it will never succeed. To solve this, a “safe zone” can be defined where the target is close enough to the center. I defined the zone by thresholdMin and thresholdMax values. I also added a weight that I can use to fine tune the movement. It’s called throttleWeight. After all, I added the already existing speed parameter to the calculation, so there’s another control parameter that acts globally. The updated controlThrottle method looks like the following at this stage:</p><pre>function controlThrottle(relativeDistanceVector) {<br>  const distanceYThresholdMin = -0.2;<br>  const distanceYThresholdMax = 0.1;<br>  const throttleWeight = 1;<br>  if (<br>    relativeDistanceVector[1] &gt;= distanceYThresholdMin &amp;&amp;<br>    relativeDistanceVector[1] &lt;= distanceYThresholdMax<br>  ) {<br>    return 0;<br>  } else {<br>    const direction =<br>      relativeDistanceVector[1] &gt; 0<br>        ? -1<br>        : relativeDistanceVector[1] &lt; 0<br>        ? 1<br>        : 0;<br>    return throttleWeight * speed * direction;<br>  }<br>}</pre><p>The next parameters are the yaw and the roll. If I only controlled the yaw, the drone would only be able to follow me when I moved around it. However, if I took a few steps to the side, the drone would lose sight of me quickly because it wouldn’t be able to see my face from the front. To prevent this issue, I had to operate both the yaw and roll together. It took me some time to find the right balance and not overdo or underdo any of the movements. Looks like this:</p><pre>function controlRollAndYaw(relativeDistanceVector) {<br>  const distanceXThresholdMin = -0.15;<br>  const distanceXThresholdMax = 0.15;<br>  const yawWeight = 0.7;<br>  const rollWeight = 0.3;<br><br>  let yaw = 0, roll = 0;<br><br>  if (<br>    relativeDistanceVector[0] &lt; distanceXThresholdMin ||<br>    relativeDistanceVector[0] &gt; distanceXThresholdMax<br>  ) {<br>    yaw =<br>      yawWeight *<br>      speed *<br>      (relativeDistanceVector[0] &lt; distanceXThresholdMin<br>        ? -1<br>        : relativeDistanceVector[0] &gt; distanceXThresholdMax<br>        ? 1<br>        : 0);<br>    roll =<br>      rollWeight *<br>      speed *<br>      (relativeDistanceVector[0] &lt; distanceXThresholdMin<br>        ? -1<br>        : relativeDistanceVector[0] &gt; distanceXThresholdMax<br>        ? 1<br>        : 0);<br>  }<br><br>  return { yaw, roll };<br>}</pre><p>The last parameter is pitching. As I mentioned before, I used the size of the face bounding box to determine the distance. After a few dry runs (not turning the propellers on but holding the drone in my hand), I found the magic number for this parameter as well, so the drone didn’t accidentally cut my face.</p><pre>function controlPitch(area) {<br>  const areaThresholdMin = 0.045;<br>  const areaThresholdMax = 0.055;<br>  const pitchWeight = 0.5;<br>  if (areaThresholdMin &lt;= area &amp;&amp; area &lt;= areaThresholdMax) {<br>    return 0;<br>  } else {<br>    return (<br>      pitchWeight *<br>      speed *<br>      (area &gt; areaThresholdMax ? -1 : area &lt; areaThresholdMin ? 1 : 0)<br>    );<br>  }<br>}</pre><p>All the control-related changes are in one place <a href="https://github.com/hunhavoc/drone-ai-demo/compare/852bc5c86e6c695c892d1eb4cfc9a05410b64235...3119bffdfe2f6a8ea4f8440f95304901d2616063">here</a>.</p><p>At this point, the timer went off. Let’s see the code in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mfS4GOpf2uUNgV4r49dyog.gif" /><figcaption>Having fun in the Supercharge office</figcaption></figure><p>The controlling algorithm is not perfect at all and has several limitations. For example, if the camera sees multiple faces, it will randomly select one of them rather than sticking with the same one. Additionally, the person being followed needs to be careful about their movements to stay within the range of the camera. Even if the person stands still without moving their head, the drone will keep swinging back and forth as it tries to find the perfect position, which is impossible to achieve. The latter issue could be solved by using a correctly parameterized compensator algorithm like PID, but I ran out of time and was already satisfied with the result.</p><p><strong>By researching and utilizing existing code and libraries, I was able to control the drone and implement face recognition within a 4-hour time frame.</strong></p><p>If you haven’t checked the code yet, here’s my Github repo for the last time: <a href="https://github.com/hunhavoc/drone-ai-demo">link</a>.</p><h3>Conclusion</h3><p>In summary, this project demonstrates that anyone can utilize AI and IoT technologies without necessarily having a background in the underlying mathematics. However, I recommend a <a href="https://tivadardanka.com/books/mathematics-of-machine-learning">book</a> written by a friend for those who are interested in delving deeper into the math behind AI and machine learning.</p><p>It is important to note that this was an experimental project and should not be considered a model for how to approach a real-life project. The project serves as a good example of how rapid prototyping with AI can be achieved using available resources.</p><p>Leave a comment, give a clap and start following me if you liked it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a75afa7240f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/supercharges-mobile-product-guide/unleashing-the-potential-of-ai-for-teaching-drones-making-advanced-technologies-accessible-to-all-a75afa7240f7">Unleashing the potential of AI for teaching drones: making advanced technologies accessible to all</a> was originally published in <a href="https://medium.com/supercharges-mobile-product-guide">Supercharge&#39;s Digital Product Guide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular + Redux — The lesson we’ve learned for you]]></title>
            <link>https://medium.com/supercharges-mobile-product-guide/angular-redux-the-lesson-weve-learned-for-you-93bc94391958?source=rss-d0abf1129dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/93bc94391958</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[angular-redux]]></category>
            <dc:creator><![CDATA[Attila Oláh]]></dc:creator>
            <pubDate>Fri, 01 Jun 2018 08:01:19 GMT</pubDate>
            <atom:updated>2018-06-01T12:31:45.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1MRvrZVPQL-r7yO6NGygg.jpeg" /></figure><p>In my first blog post I’d like to share our experiences with Redux and Angular in hope of helping out the ones who are just about to onboard with this stack. It can save you a lot of headaches if you’re familiar with Angular but Redux is completely new to you.</p><h3>Background story</h3><p>Back in late 2016 when Angular 2.0 was finally released, we were already playing with rc5 and managed to release our first app in production. Although I was impressed by Angular’s two-way data binding and the capabilities of RxJS, the two-way data binding and the principle of “we-are-so-reactive-everything-is-bound-to-everything” create a degree of dependence that fails in terms of maintainability and code readability. In addition, it was very hard to track down update loops or just to find a simple bug. I was sure that we were doing something wrong and the basic Angular setup is supposed to work.</p><p>So I did some research on the topic. I found a couple of articles that recommend to use Rx streams in services as a single source of truth. It can solve the “complete graph”-like connections issue within components and services. It was in line with our Android mobile team’s advice: consider managing your app’s state in a centralised data repository by implementing the Flux architecture.</p><p>I also found the Redux library, but like so many other developers at the time, that name was fused in my mind with React, so I thought, “Good, good, except we’re using Angular.” I stuck to this mindset until I went to the AngularUP conference in Tel-Aviv, where one of the talks was literally called <em>Angular+Redux</em>, and explained in detail how the two frameworks can be brought together. I decided to give it a try after all.</p><p><em>(I’d like to add, merely to save some face, that this concept was pretty novel back then, as Angular 2.0 had just celebrated its second month around the time the conference took place.)</em></p><p>If you’re not yet familiar with Flux and Redux or just need a short recap, don’t skip the following part. Otherwise you can jump to Angular-redux.</p><blockquote><strong><em>Short introduction into Flux architecture</em></strong></blockquote><blockquote><em>React had been on the market for about a year when Facebook announced the “Flux Architecture“:</em></blockquote><blockquote>“We found that two-way data bindings led to cascading updates, where changing one object led to another object changing, which could also trigger more updates. As applications grew, these cascading updates made it very difficult to predict what would change as the result of one user interaction. When updates can only change data within a single round, the system as a whole becomes more predictable.” — <a href="https://facebook.github.io/flux/docs/in-depth-overview.html">https://facebook.github.io/flux/docs/in-depth-overview.html</a></blockquote><blockquote><em>Let’s say the application state is global and the components’ states are local. Flux uses stores to hold global (application) state. It means that any component, anywhere in the app has access to this data repository. This is the single source of truth. Local states are not allowed to hold any data that could be needed by any other component. The store can be changed through actions only. Actions are dispatched by user interactions typically. Views’ (local) state depend on what they get from the store, and that’s how the circle closes:</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hVty0_tllTMxZ318." /><figcaption>Source: <a href="https://facebook.github.io/flux/docs/in-depth-overview.html">https://facebook.github.io/flux/docs/in-depth-overview.html</a></figcaption></figure><blockquote><strong><em>A Flux implementation: Redux</em></strong></blockquote><blockquote><em>According to the official site of Redux:</em></blockquote><blockquote>“…<strong>Redux attempts to make state mutations predictable</strong> by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.” <em>— </em><a href="https://redux.js.org/introduction/motivation">https://redux.js.org/introduction/motivation</a></blockquote><blockquote><strong>1. Single source of truth</strong></blockquote><blockquote>“The state of your whole application is stored in an object tree within a single store.”</blockquote><blockquote><em>This enables developers to, among others:</em></blockquote><blockquote><em>- easily inspect / debug the application’s state.</em></blockquote><blockquote><em>- save and load a preset state for faster development by jumping to the point where development is taking place.</em></blockquote><blockquote><em>- handle traditionally difficult functionalities corresponding to app state like undo/redo.</em></blockquote><blockquote><em>- attach a state snapshot to error reports</em>.</blockquote><blockquote><strong>2. State is read-only</strong></blockquote><blockquote>“The only way to change the state is to emit an action, an object describing what happened.</blockquote><blockquote>Because all changes are centralized and happen one by one in a strict order, there are no subtle race conditions to watch out for. As actions are just plain objects, they can be logged, serialized, stored, and later replayed for debugging or testing purposes.”</blockquote><blockquote><em>Another convenient feature of Redux is time traveling. Since the store can be mutated by actions only, the state change is predictable. If your app is completely stateless (no components can exist on their own), you can rewind or replay the history by reapplying the recorded actions one-by-one, always starting from the “default state”, and you are sure to end up in the same app state. You can even change the history by reordering or skipping some actions.</em></blockquote><blockquote><em>Check out </em><a href="https://medium.com/the-web-tub/time-travel-in-react-redux-apps-using-the-redux-devtools-5e94eba5e7c0"><em>this</em></a><em> blogpost if you are interested in details.</em></blockquote><blockquote><strong>3. Changes are made with pure functions</strong></blockquote><blockquote><em>To update the state, you write reducers. A reducer receives an action (one at a time) and the current application state and returns the updated state (modified or not), and does nothing else. Reducers are just pure functions, so you can combine them, which enables you to break down the store update logic to small chunks and merge at the end. This helps developers write maintainable code.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ivEtU668kM5UEPG-." /><figcaption>Source: <a href="https://medium.com/@abhayg772/introduction-to-redux-using-react-native-a8f1e8778333">https://medium.com/@abhayg772/introduction-to-redux-using-react-native-a8f1e8778333</a></figcaption></figure><h3>Angular-redux</h3><p>There were two popular libraries on the market at the time, which are connected to Redux in some way:</p><p><a href="https://github.com/angular-redux/store"><strong>@angular-redux</strong></a> (aka ng2-redux) uses Angular’s features to help integrate the Redux library painlessly.</p><p><a href="https://github.com/ngrx/platform"><strong>@ngrx</strong></a> is inspired by Redux but a completely new implementation. Redux’s source code is not included.</p><p>From a developer’s point of view, the two libraries work the same way. I decided to give Angular-redux a try, based on the below:</p><ul><li>Redux was already a popular library, which guarantees community support.</li><li>Redux had been stable for a while.</li><li>Really cool devtools (like <a href="https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en">redux-devtools</a>, <a href="https://github.com/evgenyrodionov/redux-logger">redux-logger</a>).</li><li>I’ve seen it working on stage :) (AngularUP conference)</li></ul><h3>Chaotic result</h3><p>We all went through the angular-redux tutorial / documentation, but it wasn’t as detailed at that time as it is today. We tried to cherry-pick the best practices from the available angular-redux documentations/tutorials/articles, but there are always things you cannot forecast. We made mistakes; nonetheless, the app was shipped on time and is running well. Here’s what we could highlight from that experience:</p><p><strong>Everything’s stored in redux store</strong></p><p>This wasn’t the best idea. We stored the form’s state, the navbar’s open/closed state, the drawers’ open/closed state, and even animation state. We should have handled those in the component’s local state and just let the app know (through actions) when something happens that should affect the whole app. For example, opening/closing a dropdown item shouldn’t trigger an action by default, but clicking a menu item is definitely something that is expected to have an effect on the app. Storing everything just generates a lot of boilerplate code, plus it gives you a lot of actions that make it hard to keep track of what’s going on.</p><p><strong>No common thinking on using Redux with Angular together</strong></p><p>Two things to discuss here: <em>store selectors</em> and <em>action dispatchers</em>.</p><p>Let’s start with store selectors. They can be placed in Angular <em>components</em> or in <em>services</em>. It’s easy to make a stand for either way. And if there isn’t a clear concept you communicate towards the team, the developers will start using both, depending on their personal decisions. We should’ve had a discussion about it and decide when to put the selector in components and when in services. Yes, both needed. However, it is not well-founded to put the selectors in all scenarios into the corresponding service as it generates a lot of boilerplate. As a rule-of-thumb I recommend to define selectors in components by default and use them in services when any logic needs to be applied before the view layer can take the data over.</p><p>Our other point: Action dispatchers. Here we have a similar dilemma, actions can be dispatched from components or services. I can offer you the same advice: define a set of rules and make make sure your team follows them. Personally I suggest to dispatch actions from components as long as all the information are available there for the action builder. In any other case dispatch them from a service where all necessary data is available.</p><p><strong>Inconsecutive action names</strong></p><p>Using actions to describe what had happened recently in the app seemed plausible to me, so:</p><ul><li>when the user clicks on the Login button, the action is ‘login button clicked’</li><li>when a list of items has arrived from the backend, the action says ‘items fetched’ or ‘item list updated’</li><li>when something goes wrong, the action is ‘error during fetching items’ or ‘password is incorrect’</li></ul><p>BUT the rest of the team started to give <strong>commands</strong> rather than reporting <strong>events:</strong></p><ul><li>‘login button clicked’ =&gt; ‘send login request’</li><li>‘item list updated’ (network response has arrived) =&gt; ‘update item list’ (update the item list in the app)</li><li>‘password is incorrect’ =&gt; ‘show incorrect password alert’</li></ul><p>I later realised that both ways work just fine, as long as you don’t mix them. Doing so we’ve managed to make:</p><ul><li>the data flow untraceable.</li><li>the new team members confused which style to follow.</li><li>hard to find out if the action you’d like to dispatch is defined already.</li></ul><p>I resonate with the event-based naming, <a href="https://hackernoon.com/dispatch-redux-actions-as-events-not-commands-4de8a92b1ea5">here</a>’s why.</p><p><strong>The more code we wrote, the more trouble we had</strong></p><p>As you may have already realised, these issues escalated to a higher level as SLOC increased:</p><ul><li>It was quite challenging to debug somebody else’s code.</li><li>It wasn’t so obvious how to extend or add functionality.</li><li>To follow what’s happening on code level was not as easy as Flux’s single data flow direction promises.</li><li>And this all lead to longer onboarding of new team members.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*_XiX0z_o6eB23h_q.jpg" /></figure><h3>Conclusion</h3><p>First of all, have a <strong>common understanding of the Flux architecture and the Redux</strong> library within the dev team. If needed, get your team to learn it first.</p><p>How much data you put in the store is up to you, but never forget: <strong>not all data needs to live there</strong>. For example, if it’s not required from business side to be able to track the steps taken by the user filling the form, then the form’s state can be handled as local state. Once the form is submitted, an action will be dispatched with the form data, so the application will know about it. Of course, if it’s necessary, you can turn each key press into an action and reducers can handle the form accordingly. Coincidentally, Angular-redux <a href="https://github.com/angular-redux/form">supports</a> managing forms. Check it out and consider using it if it fulfills your requirements.</p><p>Have a <strong>strict naming convention for the actions</strong> as described above. It doesn’t matter what style (<strong>event</strong> or <strong>command</strong>) you choose as long as it stays consistent. Don’t be shy to leave a comment on each action’s name during code review. After a while it could feel silly to argue on wording, but it’s worth the effort to keep the code consistent.</p><p><strong>Define actions and design the store</strong> in an early stage (it can even happen as early as the technical kickoff of the project) to prevent chaos. This document has to be accessible for every technician on the project. This will support the onboarding process, bug fixing phases and last but not least, the implementation phase as well.</p><p>Oh, and one last thing! <a href="https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367"><strong>Are you sure you need Redux for your project?</strong></a></p><p>Special thanks to my colleagues <strong>Andrea Lika </strong>and <strong>Máté Safranka </strong>for helping me reviewing this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93bc94391958" width="1" height="1" alt=""><hr><p><a href="https://medium.com/supercharges-mobile-product-guide/angular-redux-the-lesson-weve-learned-for-you-93bc94391958">Angular + Redux — The lesson we’ve learned for you</a> was originally published in <a href="https://medium.com/supercharges-mobile-product-guide">Supercharge&#39;s Digital Product Guide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>