<?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 MigCoder on Medium]]></title>
        <description><![CDATA[Stories by MigCoder on Medium]]></description>
        <link>https://medium.com/@migcoder?source=rss-56c03d5c986d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*V7ac3gcjN7CbaNyV.</url>
            <title>Stories by MigCoder on Medium</title>
            <link>https://medium.com/@migcoder?source=rss-56c03d5c986d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:40:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@migcoder/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[Doll — Monitor from Menu bar]]></title>
            <link>https://migcoder.medium.com/doll-monitor-from-menu-bar-e2a8cdcf4d98?source=rss-56c03d5c986d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2a8cdcf4d98</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[dolls]]></category>
            <dc:creator><![CDATA[MigCoder]]></dc:creator>
            <pubDate>Sun, 30 Jan 2022 13:37:13 GMT</pubDate>
            <atom:updated>2022-01-30T13:37:13.301Z</atom:updated>
            <content:encoded><![CDATA[<h3>Doll — Monitor from Menu bar</h3><p>Hi fellows, check out my first Mac App — <a href="https://github.com/xiaogdgenuine/Doll"><strong>Doll</strong></a>!</p><p><a href="https://github.com/xiaogdgenuine/Doll">GitHub - xiaogdgenuine/Doll: A mac app to help monitor your app badges!</a></p><p>Detail is in the repo, but in short, Doll is a tool that help you create app shortcuts in Menu bar, with <strong>Badge</strong> information!</p><p>Just like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kdk3ey71JVsFPfQi.png" /><figcaption>Doll’s function</figcaption></figure><p>It’s completly written in SwiftUI and it’s <a href="https://github.com/xiaogdgenuine/Doll">open sourced on github</a>.</p><p>I Hope you will find it helping you in your daily works, happy coding~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2a8cdcf4d98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comic Fans, Meet the KedaManga!]]></title>
            <link>https://migcoder.medium.com/comic-fans-meet-the-kedamanga-cd06b98d46e6?source=rss-56c03d5c986d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd06b98d46e6</guid>
            <category><![CDATA[comics]]></category>
            <category><![CDATA[readers]]></category>
            <category><![CDATA[kedamanga]]></category>
            <category><![CDATA[ios-apps]]></category>
            <category><![CDATA[manga]]></category>
            <dc:creator><![CDATA[MigCoder]]></dc:creator>
            <pubDate>Sun, 04 Apr 2021 10:33:36 GMT</pubDate>
            <atom:updated>2021-04-04T10:33:36.384Z</atom:updated>
            <content:encoded><![CDATA[<p>Comic books, or Manga in Japan, is my favorite thing since I’m a child, I love to collect comic books, and every little friend shares their collection, eating snacks, discussing the plot, arguing which character is more powerful…What a happy childhood ~~😗</p><p>I bought an iPad pro in 2019, I convince my self that I will use it for academic purpose but damn me, it just becomes my movie player 🤫</p><p>One day I’m really run out of my movie list and decide to read some comic books on it, then I found most of the comic viewer software in AppStore doesn’t suit my requirements:</p><ul><li>Open DRM-free comics directly(ZIP, CBZ, RAR, CBR…).</li><li>Import comics from my PC, NAS.</li><li>Only extract the required images from the archive file, not all of them.</li><li>Optimized layout for different kinds of comic books.</li><li>Correctly handle nested files so I don’t have to organize them by myself.</li><li>…</li></ul><p>So I told my self:</p><blockquote>Why not learn some iOS development skills, and make your own comic viewer?</blockquote><p>And here it comes, the <a href="https://apps.apple.com/us/app/%E5%8F%AF%E8%BE%BE%E6%BC%AB%E7%94%BB-%E6%BC%AB%E7%94%BB-%E5%9B%BE%E7%89%87%E9%98%85%E8%AF%BB%E5%99%A8/id1545372338"><strong>KedaManga</strong></a>, my first iOS app dedicated to reading comics.</p><h3>Basic features</h3><p>Just like many comic viewers, KedaManga supports some functions naturally.</p><p>Read mode: Page by page, or continuous.</p><p>Read direction: Left to Right, Right to Left, Top to Bottom, any way you want :)</p><p>Image pre-process: KedaManga will split a big image into two small ones(<strong>Portrait</strong> mode).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*RTj6W1MOpUVjXTdh-GjUKg.png" /></figure><p>or merge two small images into one(<strong>Landscape</strong> mode)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIDvLU0HSLHv97Z-T2E9YA.png" /></figure><h3>Nice page curl animation</h3><p>A nice page-turning effect that makes you feel like reading a real book.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*ilw6SLBaLOrkaVDIVxuL1Q.gif" /></figure><h3><strong>Access comics on servers</strong></h3><p>KedaManga is designed to make reading comics easier, not just about the way of displaying them, but also the way you get them.</p><p>It allows you to fetch your comics from <strong>WebDAV</strong>, <strong>Samba</strong>, <strong>FTP</strong>, and <strong>iCloud</strong> server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpGELdxp168X_t-QAxmRBQ.png" /></figure><p>Your comic collection can store on Mac, Windows, or Linux computers, KedaManga can access them directly!</p><h3><strong>Upload comics through HTTP server</strong></h3><p>You can also share comic books by starting a local HTTP server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*6qBh6nlKJyTPIuWduRBeEA.png" /></figure><p>Other devices can open this address in the browser, and upload/download resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDHPn2CIsuPCbmYzbOq0sg.png" /></figure><p>It’s really handy!</p><h3>Read directly on the server</h3><p>Developing KedaManga gives me a chance to really understand how some file formats works, ZIP, PDF, RAR…. and my favorite format among them is ZIP.</p><p>The <a href="https://en.wikipedia.org/wiki/Phil_Katz">guy</a> who invented ZIP is a genius, I spent a lot of time understanding the <a href="https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT">ZIP file format specification</a>, then I finally realize why ZIP is the most popular archive format across the internet, you can preview the ZIP content without download the whole archive!</p><p>Here is how a ZIP file looks like from technical pov:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n_shUTaA2aLFLTSM.png" /></figure><p>As you can see each file in the ZIP is positioned one after another, and there is a <strong>central directory</strong> at the end of the ZIP which told you the offset &amp; length of each individual file.</p><p>With this info and a server that allows you to download only a dedicated part of a file(<strong>WebDAV</strong> or <strong>Samba</strong> server for example), I implemented a “<strong>Stream</strong>” reading mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*x6F-2ZAYhiDtTSyBO3w5PA.gif" /></figure><p>As you can see, a <strong>2GB</strong> ZIP file in the server can be open almost instantly, and while you are browsing pages, KedaManga will download the dedicated data for these pages only, which saves you a lot of bandwidth and disk storage!</p><h3>File formats</h3><p>Currently, KedaManga supports these file formats:</p><p>ZIP, RAR, PDF, CBZ, CBR, EPUB, Folder</p><p>And you can nest them too! Put ZIP inside RAR, then put RAR into a folder? No problem, KedaManga can take care of them for you, pan from the left edge of the screen and you will see a nice navigation menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*gsmZwgNIm1La3GZdHkNVzA.png" /></figure><h3>Image formats</h3><p>KedaManga currently supports images with JPG, JPEG, PNG, GIF, APNG, WebP formats.</p><p>More are coming…</p><h3>Password book</h3><p>Inputting passwords could be the most annoying thing in the world, it’s getting worse when you need to do them on mobile 🤬!</p><p>KedaManga can’t help you avoid passwords, but it can help you remember them 🤓, and every time you open a new comic book that requires a password, KedaManga will try all these passwords first before asking you to input a new one!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*sJJ_89j0z8pfraJnXz-cGA.png" /></figure><h3>Keyboard Control</h3><p>With the new iPad release, it’s getting common that people connect and use a keyboard with iPad devices, here are some useful shortcuts you can use while in KedaManga:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2QW5lZjquCrxzG3jK-0-A.png" /></figure><h3>The「Zen」mode</h3><p>When you are reading a real book, you may lay down in bed, play some soothing music, drink hot coffee, or something else…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUs6H2phRmcexXMIZZhKWA.jpeg" /></figure><p>Now I can’t buy you a coffee when you’re reading comics on KedaManga 🥴, but I do develop a 「Zen」mode to help you concentrate on reading:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGZt10fCfqt8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGZt10fCfqt8&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/11c2889febd7e65204323664c17974b4/href">https://medium.com/media/11c2889febd7e65204323664c17974b4/href</a></iframe><p>I hope you will enjoy it, and more sound and effects are in development.</p><h3><strong>App store link</strong></h3><p><a href="https://apps.apple.com/us/app/%E5%8F%AF%E8%BE%BE%E6%BC%AB%E7%94%BB-%E6%BC%AB%E7%94%BB-%E5%9B%BE%E7%89%87%E9%98%85%E8%AF%BB%E5%99%A8/id1545372338">‎KedaManga - Comic reader</a></p><h3>The End</h3><p>KedaManga is my first iOS app, though it did take a lot of my spare time, I will keep it limit-free for a while.</p><p>If you love comics and want to give it a try, I would be more than happy to hear your feedback! 🥰🥰🥰</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd06b98d46e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prefetch, Preload- Take control from webpack]]></title>
            <link>https://migcoder.medium.com/prefetch-preload-take-control-from-webpack-26d1e0f2c3?source=rss-56c03d5c986d------2</link>
            <guid isPermaLink="false">https://medium.com/p/26d1e0f2c3</guid>
            <category><![CDATA[preloading]]></category>
            <category><![CDATA[babel-plugin]]></category>
            <category><![CDATA[prefetch]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[babel]]></category>
            <dc:creator><![CDATA[MigCoder]]></dc:creator>
            <pubDate>Tue, 04 Feb 2020 04:32:52 GMT</pubDate>
            <atom:updated>2020-02-10T05:35:10.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZ4W9TcMhfTKiSEW_O_zEA.png" /></figure><h3>Prefetch — Take control from webpack</h3><p>Webpack’s prefetch strategy is struggling me for a long time, today I will show u how to fight them.</p><p>In short, by using webpack u can do code splitting and lazy load like this:</p><pre>// In app.js <br>if (renderPageA) {<br>  import(&#39;./pageA.js&#39;).then(module =&gt; render(module.default))<br>}</pre><pre>if (renderPageB) {<br>  import(&#39;./pageB.js&#39;).then(module =&gt; render(module.default))<br>}</pre><p>Then two new chunks will be created along with app.hash.js chunk</p><p><strong><em>0.hash.js</em></strong></p><p><strong><em>1.hash.js</em></strong></p><p>if u don’t like the number in the chunk name, u can specify ur own one too:</p><pre>import(/* webpackChunkName: &#39;pageA&#39; */ &#39;./pageA.js&#39;)<br>import(/* webpackChunkName: &#39;pageB&#39; */ &#39;./pageB.js&#39;)</pre><p>the magic comment <strong>webpackChunkName</strong> set the chunk name, then u got:</p><p><strong><em>pageA.hash.js</em></strong></p><p><strong><em>pageB.hash.js</em></strong></p><p><a href="https://webpack.js.org/api/module-methods/#magic-comments">Module Methods | webpack</a></p><p>Check above link u can see more magic comments can be used, we will focus on <strong>/* webpackPrefetch: true*/</strong></p><pre>// In app.js <br>if (renderPageA) {<br>  import(/* webpackPrefetch: true */&#39;./pageA.js&#39;)...<br>}</pre><p>The <strong><em>webpackPrefetch</em></strong> comment told webpack to insert a prefetch link into HTML head when app.hash.js chunk is loaded:</p><pre>&lt;link rel=&quot;prefetch&quot; as=&quot;script&quot; href=&quot;pageA.hash.js&quot;/&gt;</pre><p>The webpack prefetch strategy is: if a JS chunk says some async-chunks need to be prefetch, then when that JS chunk loaded, immediately all the async-chunks with /* <strong>webpackPrefetch: true */</strong>is prefetched.</p><blockquote>See the problem here?</blockquote><blockquote>U don’t actually have the control on prefetch</blockquote><p>Prefetch resources take network times, and worse in mobile users, it takes money too.</p><p>If a JS chunk, say a <strong><em>search-wrapper.js</em></strong> chunk, load some async-chunks base on media query API, like <strong><em>desktop-search.js</em></strong> &amp; <strong><em>mobile-search.js</em></strong>, and u add</p><p>/* webpackPrefetch: true */</p><p>on both async-chunks, then when mobile user load <strong><em>search-wrapper.js</em></strong>, webpack will prefetch <strong><em>desktop-search.js</em></strong> for him too!</p><h3>Why webpack prefetch work like this?</h3><p>My understanding is webpack actually don’t have a choice because of the import statement like this:</p><pre>import(&#39;./pageA.js&#39;).then(module =&gt; ...)</pre><p>is an ES standard of dynamic module importing, when it executed, the browser has to fetch the pageA.js and parsing, evaluating….then resolve the module to the promise callback.</p><p>So u see webpack have no way pass prefetch control to u, the import statement is an ES standard, if webpack add some <strong>magic method</strong> on it like this:</p><pre>const a = document.getElementById(&#39;linkToPageA&#39;)</pre><pre>// This just prefetch, doesn&#39;t evaluate the JS<br>a.onmousehover = ()=&gt; import(&#39;./pageA.js&#39;).prefetch()</pre><pre>// This do parse, evaluate the JS<br>a.onclick = () =&gt; import(&#39;./pageA.js&#39;).load().then(...)</pre><p>It doesn’t feel right, right? as long as <strong>import() </strong>is the standard, it just makes people confuse…</p><h3>How we take over control of this?</h3><p><strong>Babel</strong> is my answer, to be specific it’s a babel plugin.</p><p>We already learn that webpack can modify import statement’s behavior by using some magic comments, without break the ES standards, if we can add our own magic comment, we can achieve something interest.</p><p>I write a babel plugin to generate the prefetch code for each import statement.</p><p>So if ur lazy component declares and uses like this:</p><pre><em>import </em>{ prefetchable } <em>from </em>&quot;webpack-prefetcher&quot;;</pre><pre>const lazyPageA = prefetchable(() =&gt; import(&#39;./pageA.js&#39;))</pre><pre>// This just prefetch, doesn&#39;t evaluate the JS<br>a.onmousehover = () =&gt; lazyPageA.prefetch()</pre><pre>// This do parse, evaluate the JS<br>a.onclick = () =&gt; lazyPageA.load().then(...)</pre><p>My babel plugin will transform it to:</p><pre>const lazyPageA = prefetchable(() =&gt; <br>  import(&#39;./pageA.js&#39;), <strong><em>&#39;pageA-chunk&#39;, &#39;.js&#39;</em></strong>)</pre><pre>// This just prefetch, doesn&#39;t evaluate the JS<br>a.onmousehover = () =&gt; lazyPageA.prefetch()</pre><pre>// This do parse, evaluate the JS<br>a.onclick = () =&gt; lazyPageA.load().then(...)</pre><p>Notice two extra parameters added to lazyPageA’s declaration?</p><p><strong><em>pageA-chunk </em></strong>is the chunk name, <strong><em>.js </em></strong>is the chunk extension, they are extracted from the import statement:</p><pre>import(‘./pageA.js’)</pre><p>Let check how <strong><em>prefetchable()</em></strong> implemented:</p><pre><em>export function </em>prefetchable(importFunc, chunkId, chunkExtension){<br>  <em>return </em>{<br>    load: importFunc,<br>    prefetch: as =&gt; Prefetcher.prefetch(chunkId, chunkExtension, as)<br>  }<br>}</pre><p><strong>Prefetcher</strong> is a simple helper class that contains the manifest of webpack output, and can help us on inserting the prefetch link:</p><pre>export class Prefetcher {<br>  static manifest = {<br>    &quot;pageA.js&quot;: &quot;/pageA.hash.js&quot;,<br>    &quot;pageA.css&quot;: &quot;/pageA.hash.css&quot;,<br>    &quot;app.js&quot;: &quot;/app.hash.js&quot;,<br>    &quot;index.html&quot;: &quot;/index.html&quot;<br>  }</pre><pre>static function prefetch(chunkId, chunkExtension, as) {<br>    const link = document.createElement(&#39;link&#39;)<br>    link.rel = &quot;prefetch&quot;<br>    link.as = as<br>    link.href = Prefetcher.manifest[chunkId + chunkExtension]<br>    document.head.appendChild(link)<br>  }<br>}</pre><p>U can extract the manifest from webpack by some manifest plugins, I leave this to u cause it’s out scope here.</p><p>U can see the limit here, the <strong><em>chunkId </em></strong>we use for prefetch<strong><em> </em></strong>is extracted from<em> </em><strong><em>webpackChunkName </em></strong><em>comment, </em>what if u don’t set that name? The answer is u have to set one, otherwise, this plugin will give u one, and it doesn’t handle chunk name confliction, so if u have two js with the same name, things will mess-up:P.</p><p>If u don’t like the <strong><em>webpackChunkName</em></strong>, u can use <a href="https://github.com/sebastian-software/babel-plugin-smart-webpack-import">babel-plugin-smart-webpack-import</a> to generate a better chunk name automatically.</p><h3>How the plugin implemented?</h3><p>The code is too long to paste here, so I leave it in GitHub:</p><p><a href="https://gist.github.com/xiaogdgenuine/921c643bc4eedd029cdf2bfe11c79a00">https://gist.github.com/xiaogdgenuine/921c643bc4eedd029cdf2bfe11c79a00</a></p><p>Overall, the plugin works like this:</p><ul><li>Gather all the <strong><em>prefetchable(() =&gt; import(args))</em></strong> statements in ur code</li><li>Find the <strong><em>chunkId, chunkExtension </em></strong>from the<strong><em> import() </em></strong>statement</li><li>Add <strong><em>chunkId</em></strong>, <strong><em>chunkExtension</em></strong> to the end of <strong><em>prefetchable()</em></strong> call</li></ul><p>Pls note that it’s just a few days works for a proof of concept, so</p><p><strong>Be careful to use it in prod!!!</strong></p><h3>Is there a package for all these?</h3><p>Yes!! Check my first npm package here: <a href="https://www.npmjs.com/package/webpack-prefetcher">https://www.npmjs.com/package/webpack-prefetcher</a></p><h3>I feel it’s kinda overkill, can’t webpack implement this directly?</h3><p>If u want webpack team to have this feature implemented, instead of my hacky way, pls share ur voice here~:</p><p><a href="https://github.com/webpack/webpack/issues/8470">https://github.com/webpack/webpack/issues/8470</a></p><h3>Special thanks:</h3><p>The inspiration for this plugin comes from:</p><p><a href="https://github.com/sebastian-software/babel-plugin-smart-webpack-import">https://github.com/sebastian-software/babel-plugin-smart-webpack-import</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26d1e0f2c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reflection — Get variable name in JavaScript]]></title>
            <link>https://migcoder.medium.com/reflection-get-variable-name-in-javascript-64ed595701eb?source=rss-56c03d5c986d------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ed595701eb</guid>
            <category><![CDATA[reflections]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[MigCoder]]></dc:creator>
            <pubDate>Sat, 19 May 2018 01:18:09 GMT</pubDate>
            <atom:updated>2018-06-19T02:06:43.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Yeah you may ask, what’s the point about <strong><em>Get variable name in JavaScript?</em></strong></p><p>Well, in our daily programming work, we often need to write functions, inside the function we always want some valid input argument when it’s invoked, so it’s very common to throw some error messages when a wrong argument got passed to the function, and it’s better to contain the argument name in that message to help the caller understand which argument is wrong.</p><p>There is many ways to generate these error messages, the first one come in to our mind could probably be:</p><pre>function add(x, y) {<br>   if (x === null || x === undefined || isNaN(parseFloat(x)))<br>     throw new Error(`<strong><em>x is not a valid number</em></strong>`);<br>   <br>   if (y === null || y === undefined || isNaN(parseFloat(y)))<br>     throw new Error(`<strong><em>y is not a valid number</em></strong>`);</pre><pre>   return x + y;<br>}</pre><p>It works very well, but it’s lack of maintainability, what if during the code refactor you change the <strong><em>x, y</em></strong> to be <strong><em>a, b</em></strong>?</p><p>IDE can help us to make sure update the reference of arguments if you reference them explicitly, but them can’t help you to update the argument name in your error message!</p><p>If we can get the argument name here, we can solve this problem, you can get properties info of an object easily in JavaScript by using <strong><em>Object.keys</em></strong> or <strong><em>Reflection API</em></strong>, but there is not Reflection API in JavaScript can help you to get such name…</p><blockquote>If we can’t do it with the way we known, we wrap it and do it with the way we known!</blockquote><p>The major art of programming is all about wrapping, if we can’t get a variable name directly, why don’t we try to wrap that variable into an object first?</p><pre>function add(x, y) {<br>    // After you wrap a variable into an object<br>    // It will be the first and the only property of that object<br>    const name = obj =&gt; Object.keys(obj)[0];</pre><pre>    if (x === null || x === undefined || isNaN(parseFloat(x)))<br>      throw new Error(`${<strong><em>name({x})</em></strong>} is not a valid number`);</pre><pre>    if (y === null || y === undefined || isNaN(parseFloat(y)))<br>      throw new Error(`${<strong><em>name({y})</em></strong>} is not a valid number`);</pre><pre>    return x + y;<br>}</pre><p>Well, you may ask ‘What about nest object? Like an options object?’, emmm… it’s simple:</p><pre>function add(options) {<br>    const {x, y} = options;<br>    const name = obj =&gt; Object.keys(obj)[0];</pre><pre>    if (x === null || x === undefined || isNaN(parseFloat(x)))<br>      throw new Error(`${<strong><em>name({options})</em></strong>}.${name({x})} is not a valid number`);</pre><pre>    if (y === null || y === undefined || isNaN(parseFloat(y)))<br>      throw new Error(`${<strong><em>name({options})</em></strong>}.${name({y})} is not a valid number`);</pre><pre>    return x + y;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ed595701eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between render and component prop on React Router v4]]></title>
            <link>https://migcoder.medium.com/difference-between-render-and-component-prop-on-react-router-v4-368ca7fedbec?source=rss-56c03d5c986d------2</link>
            <guid isPermaLink="false">https://medium.com/p/368ca7fedbec</guid>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[anonymous-function]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[MigCoder]]></dc:creator>
            <pubDate>Fri, 18 May 2018 10:19:33 GMT</pubDate>
            <atom:updated>2021-03-01T08:35:18.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmpIY4sEby8037bht38VhQ.jpeg" /></figure><p>So recently I’m reading the docs of React-Router, and I’m quite confuse about <strong>Route</strong> component’s <strong>render</strong> and <strong>component</strong> prop, the doc say for <strong>component </strong>prop:</p><blockquote>When you use component (instead of render or children, below) the router uses <a href="https://facebook.github.io/react/docs/react-api.html#createelement">React.createElement</a> to create a new <a href="https://facebook.github.io/react/docs/rendering-elements.html">React element</a> from the given component. That means if you provide an inline function to the componentprop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).</blockquote><p>Quite confuse isn’t it? But I finally figure it out.</p><p>The key to understand this is the statement “<strong>provide an inline function to the component prop</strong>”</p><p>We all know that Route component will re-render when the location changed, and react will compare the old and new virtual DOM tree, get some diff result and apply to the real DOM.</p><p>And react will try it’s best to reuse the DOM node, unless the <strong>type</strong> or <strong>key</strong> prop of the new ReactElement is changed.</p><p>So</p><pre>// 1.<br>const componentA = React.createElement(AppComponent, props)<br>const componentB = React.createElement(AppComponent, props)<br>console.log(componentA.type === componentB.type)             // true</pre><pre>// 2.<br>const componentA = React.createElement(() =&gt; &lt;AppComponent /&gt;, props)<br>const componentB = React.createElement(() =&gt; &lt;AppComponent /&gt;, props)<br>console.log(componentA.type === componentB.type)             // false</pre><p>All ReactElements created by <strong>way 1</strong> have the same type(AppComponent), but they don’t have the same type if they are all created by <strong>way 2</strong>.</p><p>Why?</p><p>Because there is always a new anonymous function created in the way 2 when the parent component’s(The component that contains Route component) render method got invoked, so the <strong>type of new&amp;old ReactElement</strong> is two different instances of the <strong>anonymous function</strong></p><pre>() =&gt; &lt;AppComponent /&gt;</pre><p>So in React’s point of view, there are different types of element and should be treat with <strong>unmount old &gt; mount new</strong> operation when an re-render happen, that means every state or changes you made on the old component got loss everytime the parent component re-render.</p><p>But why the <strong>render</strong> prop can avoid the unmount and mount behavior? It’s an anonymous function too!?</p><p>Here I would like to refer some source code of Route component’s render method:</p><pre>if (component)<br>  // We already know the differences for these two:<br>  // React.createElement(AppComponent)<br>  // React.createElement(() =&gt; &lt;AppComponent /&gt;)<br>  return match ? React.createElement(component, props) : null</pre><pre>if (render)<br>  return match ? <strong>render(props)</strong> : null</pre><p><strong>render</strong> prop is a function that return an ReactElement when invoked, now stop and spent few secs to think about - <strong><em>what’s the type of that returned element?</em></strong></p><pre>&lt;Route render={() =&gt; &lt;AppComponent /&gt;}&gt;&lt;/Route&gt;</pre><p>It’s AppComponent, <strong><em>not the anonymous function wrapper</em></strong>! Because after jsx compiled we got:</p><pre>if<br>  <strong>render</strong> = () =&gt; React.createElement(AppComponent)</pre><pre>then<br>  <strong>render()</strong> = React.createElement(AppComponent)</pre><pre>if<br>  React.createElement(<strong>render</strong>) =<br>    React.createElement(() =&gt; React.createElement(AppComponent))</pre><pre>then<br>  React.createElement(<strong>render()</strong>) =<br>    React.createElement(React.createElement(AppComponent))</pre><p>So when you use render instead of component prop, the type of element that <strong>render prop</strong> function return will not change on each render, even there always an new <strong>anonymous function instance</strong> created on each parentElement.render() call.</p><p>On my point of view, you can achieve the same behavior that render prop does with component prop by giving a name to the anonymous function and put it outside the parent’s render method:</p><pre>// Put this line outside render method.<br>const CreateAppComponent = () =&gt; &lt;AppComponent /&gt;</pre><pre>// Inside render method<br>render(){<br>  return &lt;Route component={CreateAppComponent}/&gt;<br>}</pre><p>So the conclusion is, there is not performance different between component and render prop if you are use component={AppComponent} directly, if you want to assign some props to AppComponent, use render={() =&gt; &lt;AppComponent {...props}/&gt; } instead of component={() =&gt; &lt;AppComponent {...props}/&gt; }</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=368ca7fedbec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>