<?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 Luke on Medium]]></title>
        <description><![CDATA[Stories by Luke on Medium]]></description>
        <link>https://medium.com/@tranphuocloc070699?source=rss-92b3c40d4a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uu0KHGu6I2J-P25janIBvg.jpeg</url>
            <title>Stories by Luke on Medium</title>
            <link>https://medium.com/@tranphuocloc070699?source=rss-92b3c40d4a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:48:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tranphuocloc070699/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[Day 3 and 4 of 100 Days of SwiftUI]]></title>
            <link>https://medium.com/@tranphuocloc070699/day-3-and-4-of-100-days-of-swiftui-31fe2dce3c0a?source=rss-92b3c40d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/31fe2dce3c0a</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Luke]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 10:05:34 GMT</pubDate>
            <atom:updated>2026-10-04T10:05:34.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JR48iQ6fRFUEEUuN3HobgQ.jpeg" /></figure><p>Day 3 didn’t have much new for me, so I’m merging it with day 4.</p><p>I’ve been coding for 3 years, mostly Java, a bit of JS. So half of this was “yeah, I know this.” Here’s what I noted down.</p><h4>Dictionary</h4><p>If a key doesn’t exist, Swift doesn’t give you null and hope for the best. You get an optional, so you have to handle it. Or you set a default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsMmbU9NW5cVR5QQb0cYNg.png" /></figure><p>I’d use this for config values. Missing key, use a fallback, move on.</p><h4>Set</h4><p>Same as HashSet. No duplicates, and lookup is fast. I&#39;ve seen code that loops through a list just to check &quot;did we already handle this ID?&quot;. A Set does that in one line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCZtqCzuMigjVk6igckbvQ.png" /></figure><h4>Enum</h4><p>Nothing special if you’ve used enums in Java. It just replaces strings like &quot;PENDING&quot; so nobody types &quot;Pending&quot; by accident.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCjd-Bkb-sKoXztLf95M_Q.png" /></figure><h4>Struct and class</h4><p>This was the confusing one. In Java and JS, objects are shared references. In Swift:</p><ul><li>struct: copied when you assign it</li><li>class: shared, same object</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XewIpphJp3nxwbuUe6ujuQ.png" /></figure><p>But with a struct, let locks everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeL21KOCKbjGYUDIau73Yg.png" /></figure><p>My rule for now: struct for plain data (like a response from an API), class when many places need to share the same object.</p><h4>static</h4><p>Same as Java. One value belongs to the type, and every file sees it. I’d keep it for constants. A changing static value is shared state, and that’s usually trouble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Phps57T5zNhgEc2VT9kkGA.png" /></figure><h4>deinit, ARC, weak</h4><p>Java has a garbage collector, so I never thought about this. Swift counts references. When the last strong reference is gone, deinit runs.</p><p>The problem is when two objects hold each other. Neither count reaches 0, so both stay in memory forever. Putting weak on one side fixes it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0gkzjNqk0yx12FcbKu3vg.png" /></figure><p>I think I’ll hit this later with closures and self.</p><h4>Protocol and extension</h4><p>Protocol is basically an interface. I used interfaces for the repository layer at work, and I’d do the same here: real one for the app, fake one for tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UO6QxhwmCX1c-O9PpJJHXA.png" /></figure><h4>if let and guard let</h4><p>if let: the value only exists inside the braces.<br> guard let: you must leave (return, throw...) if it&#39;s nil, and the value is available after.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ML-duYCLQbRtdomGOHmhoQ.png" /></figure><p>I already do “check first, return early” in Java. Swift just forces it.</p><h4>That’s it</h4><p>Biggest new things for me: optionals, struct vs class, and ARC.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31fe2dce3c0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 2 of Learning Swift: Boolean, Array and small tips]]></title>
            <link>https://medium.com/@tranphuocloc070699/day-2-of-learning-swift-boolean-array-and-small-tips-27c0316a533f?source=rss-92b3c40d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/27c0316a533f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Luke]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 08:05:24 GMT</pubDate>
            <atom:updated>2026-10-02T08:05:43.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FI1_EKcYhqs0qe7MVVxWfg.png" /></figure><p>Hi everyone, here’s what I learned today.</p><p>Honestly, not much. I already know booleans, arrays, and the other basic types, so I used today to dig into the functions I reach for most. Still, the course left two bonus quotes worth sharing.</p><p>Joseph Campbell said, <em>“Computers are like Old Testament gods: lots of rules and no mercy.”</em> And Lynch’s Law says, <em>“When the going gets tough, everyone leaves.”</em></p><p>So I hope you’re tough enough to stay with me.</p><h3>Array</h3><p>Here are the functions I use most, and the surprises I found along the way.</p><h4>forEach and for</h4><p><strong>Need the index?</strong> Use enumerated(). It gives you both the index and the item in one loop. (User is a simple struct with name, age, role, and isActive. The full code is in the next screenshot.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*rI6PmFNbX38YvTo5c-H7NQ.png" /><figcaption>Need the index? Use enumerated()</figcaption></figure><p><strong>Need to exit early?</strong> Use for, not forEach. This one caught me out. forEach takes a closure, not a loop, so return only leaves that single closure call. It acts like continue, and the loop still runs to the very end. In a plain for loop, break, continue, and return all work as you&#39;d expect. (We&#39;ll learn closures later.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*xbM-XoP8nBIE4Fb_8ym7hg.png" /><figcaption>return inside forEach acts like continue.</figcaption></figure><p>Here’s the proof: even after the user older than 40, the loop kept going.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WK_Zvy3hyOa1vI0kOkzyAg.png" /><figcaption>The loop kept going to the end.</figcaption></figure><h4>map and compactMap</h4><p>map has three forms, from longest to shortest:</p><ul><li>The full form: users.map { user in user.name }</li><li>The shorthand: users.map { $0.name }. $0 is the first argument, so you don&#39;t have to name it. If the closure takes more parameters, use $1, $2, and so on.</li><li>The key path: users.map(\.name). This is the shortest, but it can only read a property. You can&#39;t do anything like \.name += &quot;something&quot;.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*8mqjYlZZNmUOrEXsrRYDww.png" /><figcaption>Longest to shortest.</figcaption></figure><p>compactMap is map plus automatic removal of nil. For example, converting [&quot;1&quot;, &quot;x&quot;, &quot;3&quot;, &quot;four&quot;] to Int gives [1, 3], because Int(&quot;x&quot;) is nil and gets dropped. JavaScript has no direct equivalent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*ERvP40WCPggJ6sZPeaH-jQ.png" /><figcaption>nil is dropped automatically.</figcaption></figure><h4>reduce</h4><p>Here’s the fastest way I found to sum numbers: pass the operator itself. numbers.reduce(0, +) replaces numbers.reduce(0) { acc, n in acc + n }.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*Hz9aARVuvX6Zh_F6Bh1Wkg.png" /><figcaption>Pass the operator itself.</figcaption></figure><h4>some, every, includes</h4><p>Swift names them differently:</p><ul><li>includes → contains(3)</li><li>some → contains { $0.role == &quot;pm&quot; }</li><li>every → allSatisfy { $0.age &gt;= 18 }</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*zLmenAv1N8cD3RHzbZKVrw.png" /><figcaption>Swift’s names for some, every, includes.</figcaption></figure><h4>filter</h4><p>No tricks here, but it chains nicely with map. For example, filter the active users, then map(\.name) to get their names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*DUmKMMh8B4tWh0ZfOnIfMQ.png" /><figcaption>Chain filter then map.</figcaption></figure><h4>sorted</h4><p>sorted() returns a new copy, while sort() changes the original array in place (and needs var), so use it carefully.</p><p>For a quick sort, pass by: &gt; or by: &lt;. To sort by several keys, compare tuples: ($0.age, $0.name) &lt; ($1.age, $1.name).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*s20ZsrxNfQ42wNv4heMo6A.png" /><figcaption>Copy vs in place.</figcaption></figure><h4>Copy, add, and remove</h4><p>Nothing new in add and remove, but one thing is worth remembering: <strong>arrays are copied, not shared</strong>. If you do var b = a and then b.append(4), a stays unchanged. JavaScript would share the reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*14ucOEWS1LmzvVUBOuzI8Q.png" /><figcaption>Arrays are copied, not shared.</figcaption></figure><h3>Boolean</h3><p>Two small tricks made me smile:</p><ul><li>toggle() flips a Bool in place, so you can write isMuted.toggle() instead of isMuted = !isMuted.</li><li>?? treats nil as false for an optional Bool?. For example, flags.filter { $0 ?? false }.count counts only the true values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*GTx3x91zIMDp7AbD_ifcCg.png" /><figcaption>toggle() and ??.</figcaption></figure><p>That’s all for today. Thanks for reading, and see you in the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27c0316a533f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 1 of Learning Swift: Variables, Constants, Strings and Numbers]]></title>
            <link>https://medium.com/@tranphuocloc070699/day-1-of-learning-swift-variables-constants-strings-and-numbers-8dedc2d5a502?source=rss-92b3c40d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dedc2d5a502</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Luke]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 07:16:37 GMT</pubDate>
            <atom:updated>2026-10-01T07:16:37.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZoF6kzpf9GqDZ0Plh_ruQ.jpeg" /></figure><p>I’ve been building mobile apps with Flutter for a while, So why am I learning Swift now?</p><p>One reason: <strong>performance</strong>. At first I looked at Rust, since you can build for multiple platforms with it. But I felt nothing beats a native language, so I picked Swift instead.</p><p>I’m following <a href="https://www.hackingwithswift.com/100/swiftui">100 Days of SwiftUI</a> by Paul Hudson. A lot of people recommend it, and now I see why. Even with mobile experience, I enjoyed it, not only for the knowledge but also for the friendly way he teaches.</p><p>This series is my learning log. Here’s Day 1.</p><h3>Setup</h3><p>You can create a project in Xcode, but I prefer the command line. I’m more of a keyboard person than a mouse person.</p><pre>swift package init --type executable<br>swift run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*lLTnnp9PA3NyBiHpbFtf5g.png" /></figure><p>if you know JavaScript:</p><ul><li>Package.swift ≈ package.json. It manages the app name and dependencies.</li><li>.build ≈ node_modules. It&#39;s auto-generated, holds dependencies and compiled output, and is already in .gitignore.</li><li>Sources is where you&#39;ll spend most of your time.</li></ul><p>swift run builds the project and prints Hello, World! in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lozc_9hKf3GvHya4qm8NhA.png" /></figure><h3>Variables: var vs let</h3><ul><li>var means <em>vary</em>. You can change it later.</li><li>let is a constant. You can&#39;t change it after you set it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjeL4o6JCNJ8jr1ZzY8Gdg.png" /></figure><p>and you can use \() to put a variable inside a string, still hard for me to remember.</p><p>Another thing, you can’t mix type in Swift</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*fAUEzdQmJM44f7NOWb6x6A.png" /></figure><p>It was annoying at first, but it makes sense: no hidden conversions, fewer hidden bugs.</p><h3>Day 1 takeaway</h3><p>Swift is strict, but the strictness protects you. The compiler catches mistakes early.</p><p>This series is also a challenge for me: <strong>I’m coding everything by hand while I learn.</strong> It feels like detoxing from an addiction, and the poison is AI. Typing every line myself is slow and sometimes frustrating, but that’s the point. I hope I have enough patience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dedc2d5a502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Javascript to Flutter: Installing, Creating and Folder Structure]]></title>
            <link>https://medium.com/@tranphuocloc070699/from-javascript-to-flutter-installing-creating-and-folder-structure-89954a925350?source=rss-92b3c40d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/89954a925350</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Luke]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 13:44:48 GMT</pubDate>
            <atom:updated>2026-07-14T13:45:39.807Z</atom:updated>
            <content:encoded><![CDATA[<h3>From JS to Flutter: Installing, Creating and Folder Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrrLCtgg4RAe3bRoIG2ZQw.png" /></figure><p>When I started learning Flutter, I did what everyone does.</p><p>I searched YouTube.</p><p>I opened the official documentation.</p><p>I watched tutorial after tutorial.</p><p>After a while, I noticed something.</p><p>Almost every tutorial assumes you’re completely new to programming.</p><p>There’s nothing wrong with that. But after spending several years writing JavaScript, I didn’t need someone to explain what a package manager was.</p><p>What I really wanted was this:</p><blockquote>Explain Flutter as if I already know frontend</blockquote><p>I couldn’t find that series, so I decided to write it myself.</p><p>This series is basically my notes after reading the official Dart and Flutter documentation, watching lots of tutorials, and making plenty of mistakes along the way.</p><p>If you’re a React, Vue, or JavaScript developer, I hope this saves you some time.</p><p>Flutter is written by Dart, a language kinda like Java, I think so. When I run the project, Dart will goes from top to bottom of every file and then compile it into native code (depend on what’s you build). Like If you run on ios device, it will compile to swift, etc…</p><p>Let’s begin with the first chapter.</p><h3>Installation</h3><p>Before installing Flutter, there’s one thing I wish someone had told me.</p><p>The official documentation recommends downloading the Flutter SDK directly onto your computer, and there’s absolutely nothing wrong with that.</p><p><a href="https://docs.flutter.dev/get-started/install">https://docs.flutter.dev/get-started/install</a></p><p>However, it reminded me of installing Node.js manually. It works perfectly fine until one day you need another version for a different project.</p><p>That’s why I chose <strong>FVM (Flutter Version Manager)</strong> instead.</p><p>If you’ve used JavaScript before, just think of it as <strong>NVM for Flutter</strong>. It lets you switch Flutter versions for different projects without reinstalling everything. From what I’ve seen, this is also how most mobile developers manage their Flutter SDK.</p><p>You can install it here:</p><p><a href="https://fvm.app/">https://fvm.app</a></p><p>Once everything is installed, run:</p><pre>fvm flutter doctor</pre><p>If everything looks good, you’re ready to go.</p><p>One small tip that would’ve saved me some time: if you’re only planning to build an iOS application, you don’t need Android Studio. VS Code with the Flutter and Dart extensions is enough for getting started. Those extensions provide syntax highlighting, code completion, debugging support, and a few handy Flutter commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*lZTLjA5PQUqPkmJ0875S1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*vh8pqKMkBeTY3s1inofksw.png" /></figure><h3>Creating Your First Project</h3><p>Creating a Flutter project is surprisingly simple.</p><p>Open VS Code, press <strong>Cmd/Ctrl + Shift + P</strong>, and search for <strong>Flutter</strong>.</p><p>Choose <strong>Flutter: New Project</strong>, select <strong>Application</strong>, then pick a folder where you’d like to create it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*e4-CqPJfZPFekM8Y7q6ckA.png" /></figure><p>A few seconds later, Flutter generates the project for you.</p><p>Then I opened the project and immediately had my first question.</p><p><em>“Why are there so many folders?”</em></p><h3>Understanding the Folder Structure</h3><p>At first glance, a Flutter project looks much bigger than a typical React project, here’s what I learned after spending some time with Flutter: you only need to understand a few things in the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*szOs-QDV7_jPZB1mw8ewEw.png" /></figure><p>The most important folder is <strong>lib/</strong>.</p><p>This is where you’ll write almost all of your application code. If you’re coming from React, you can think of it as your <strong>src/</strong> folder. Inside it, you’ll find <strong>main.dart</strong>, which is the application’s entry point, similar to <strong>main.tsx</strong> in a React application.</p><p>The next important file is <strong>pubspec.yaml</strong>.</p><p>If you’ve worked with JavaScript before, it’ll immediately remind you of <strong>package.json</strong>. It contains your project’s dependencies, metadata, assets, and fonts. One difference is that Flutter requires you to explicitly declare your assets and fonts before using them.</p><p>You’ll also notice a file named <strong>pubspec.lock</strong>. You can think of it as Flutter’s version of <strong>package-lock.json</strong>. Most of the time, you won’t edit it manually.</p><p>The remaining files aren’t very important on your first day, but it’s useful to know what they do.</p><ul><li><strong>build/</strong>: Similar to dist/ or build/ in frontend projects. Flutter stores generated and compiled files here. If you delete it, Flutter will recreate it.</li><li><strong>.dart_tool/</strong>: Stores build caches and package resolution data. It’s closer to node_modules/.cache than node_modules itself.</li><li><strong>analysis_options.yaml</strong>: Contains linting and analyzer rules, similar to an ESLint configuration.</li><li><strong>.metadata</strong>: Stores information about the Flutter project, such as the Flutter version and migration state.</li></ul><p>Finally, you’ll see several platform folders like <strong>android/</strong>, <strong>ios/</strong>, <strong>web/</strong>, <strong>macos/</strong>, <strong>windows/</strong>, and <strong>linux/</strong>.</p><p>You write your application once inside the <strong>lib/</strong> folder. When you build the project, Flutter compiles your Dart code into native machine code and packages it inside the corresponding platform project.</p><p>For example, building for Android produces an APK or AAB using the android/ project. Building for iOS packages the exact same application through the ios/ project. The same idea applies to desktop and web.</p><p>The important thing to remember is that you aren’t writing six different applications. You’re writing one application, and Flutter takes care of packaging it for each platform.</p><h3>Wrapping Up</h3><p>Throughout this series, I’ll keep explaining Flutter from the perspective of a frontend developer. Whenever possible, we’ll start with something familiar from JavaScript, then see how Flutter solves the same problem. I’ll also share the mistakes I made and the little things I wish someone had told me earlier.</p><p>If you think I’m moving too fast or spending too much time on a topic, let me know. I’m still learning too, and I’d love to make this series useful for anyone making the same journey.</p><p>See you in the next chapter!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89954a925350" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modals: A Story of Simplicity and Scale]]></title>
            <link>https://medium.com/@tranphuocloc070699/modals-a-story-of-simplicity-and-scale-80b60ada6506?source=rss-92b3c40d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/80b60ada6506</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Luke]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 05:07:58 GMT</pubDate>
            <atom:updated>2025-08-01T05:07:58.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtJj_QcqlHHxkEWx9DtsHQ.png" /><figcaption>Thumbnail</figcaption></figure><p>A<em> story of two philosophies in frontend development . One destined for chaos, the other for elegance.</em></p><p><strong>The Birth of Two Approaches</strong></p><p>In the world of frontend development, two approaches to modal management emerged. One would become a source of endless frustration and technical debt. The other would rise as a beacon of clean architecture and developer productivity.</p><p><strong>The Old Way: A Life of Struggle</strong></p><p>The first approach was born of necessity but cursed with inefficiency. Every component that needed a modal carried the same burden — the endless ritual of local state management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XRSLDmfwcMGQOJCG1lQzQ.png" /><figcaption>The Old Way To Implement A Modal</figcaption></figure><p>Like merchants forced to carry heavy goods across endless desert roads, developers found themselves writing the same lines repeatedly. The ritual never ended.</p><pre>useState(false), setIsModalOpen(true), setIsModalOpen(false)</pre><p><strong>The New Way: A Vision of Excellence</strong></p><p>But there was another philosophy — one that challenged everything developers thought they knew about modal management. Built on principles of centralization and simplicity, this approach posed a fundamental question: What if modals could be managed globally, with minimal local state?</p><p>The foundation rested on a powerful concept — the Modal Container and global state management.</p><pre>import {Dialog, DialogContent, DialogTitle} from &quot;../ui/dialog&quot;;<br>import {useModal} from &quot;./use-modal&quot;;<br><br>const ModalContainer = () =&gt; {<br>  const {isOpen, view, closeModal,} = useModal();<br><br>  function onModalClose(open: boolean) {<br>    if (!open) closeModal();<br>  }<br><br>  return (<br>      &lt;Dialog open={isOpen} onOpenChange={onModalClose}&gt;<br>        &lt;DialogTitle title={&quot;Dummy Comp&quot;}&gt;&lt;/DialogTitle&gt;<br>        &lt;DialogContent&gt;<br>          {view}<br>        &lt;/DialogContent&gt;<br>      &lt;/Dialog&gt;<br>  );<br>};<br><br>export default ModalContainer;</pre><p>Your useModal global state hook — you can use any state management you prefer (Redux, Context API, etc.). In this example,I use Zustand.</p><pre>import {create} from &quot;zustand/react&quot;;<br>import React from &quot;react&quot;;<br><br>type ModalType = {<br>  view?: React.ReactNode;<br>  isOpen: boolean;<br>  openModal: () =&gt; void;<br>  closeModal: () =&gt; void;<br>  setView: (payload: React.ReactNode) =&gt; void;<br>}<br><br>export const useModal = create&lt;ModalType&gt;((set) =&gt; ({<br>  isOpen: false,<br>  openModal: () =&gt; set(() =&gt; ({isOpen: true})),<br>  closeModal: () =&gt; set(() =&gt; ({isOpen: false})),<br>  setView: (payload: React.ReactNode) =&gt; set(() =&gt; ({view: payload})),<br>}));</pre><p>At the application’s foundation, the Modal Container was integrated:</p><pre>import &#39;./App.css&#39;<br>import ModalContainer from &quot;./components/modern_code/modal-container&quot;;<br>import ModalExample from &quot;./components/modern_code/modal-example&quot;;<br><br>function App() {<br><br>  return (<br>      &lt;&gt;<br>        &lt;ModalContainer/&gt;<br>        &lt;ModalExample/&gt;<br>      &lt;/&gt;<br>  )<br>}<br><br>export default App</pre><p>Components could now summon modals with elegant simplicity:</p><pre>import {useModal} from &#39;./use-modal&#39;;<br><br>const ModalExample = () =&gt; {<br>  const {openModal, closeModal, setView, isOpen} = useModal();<br><br>  function onToggleModal() {<br>    if (isOpen) {<br>      closeModal();<br>    } else {<br>      setView(&lt;div&gt;Modal content&lt;/div&gt;)<br>      openModal();<br>    }<br>  }<br><br>  return (<br>      &lt;div&gt;<br>        &lt;button onClick={() =&gt; onToggleModal()}&gt;<br>          Open Modal<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>  );<br>};<br><br>export default ModalExample;</pre><p><strong>The Benefits Realized</strong></p><p><strong>End of Redundancy</strong>: No more scattered <em>useState(false)</em> across files, no more prop drilling.<br><strong>Scalability</strong>: New modals required only adding entries to the registry and calling <em>openModal()</em>.<br><strong>Consistency</strong>: Modal behavior became predictable across the entire application.</p><p><strong>Conclusion</strong></p><p>Years passed, and the two approaches lived different lives. The first left frustrated developers, bloated components, and technical debt. The second grew stronger with time — more productive developers, maintainable code, scalable applications.</p><p>The fundamental truth emerged: <em>sometimes the most profound improvements come not from adding complexity, but from removing it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80b60ada6506" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Icon Consistency in React: Tips and Best Practices]]></title>
            <link>https://medium.com/@tranphuocloc070699/icon-consistency-in-react-tips-and-best-practices-b9e9e7ae2c2b?source=rss-92b3c40d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e9e7ae2c2b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Luke]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 09:33:56 GMT</pubDate>
            <atom:updated>2024-12-12T09:33:56.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*336ZdbLlvDI7-EPaHcseyQ.png" /><figcaption>Icon Consistency In React</figcaption></figure><p>As a fresh developer, you might install <strong>react-icontify</strong> (or a similar library) and import icons directly whenever you need them. This works fine at first, but what happens when you need to change an icon — for example, switching an “eye” icon to “eyeOff”? You’d have to manually update every single component where that icon is used.</p><p>This approach can quickly become tedious and error-prone, especially as your app grows.</p><p>In this post, I’ll share a better way to manage icons in your React app — making your icons consistent, easy to maintain, and ensuring you can handle changes effortlessly. With this approach, you’ll not only improve your code quality but also take a step closer to becoming a better developer.</p><p><strong>Icon.tsx</strong></p><pre><br>import React, { useMemo } from &quot;react&quot;;<br>import {<br>  Plus<br>} from &quot;lucide-react&quot;;<br>import NextImg from &quot;next/image&quot;;<br><br>export const icons = {<br>  plus: &lt;Plus /&gt;,<br>  google_local: &quot;/assets/images/google-icon.svg&quot;,<br>} as const;<br><br>interface Props {<br>  name: keyof typeof icons | string;<br>  className?: string;<br>  size?: number;<br>  onClick?: (e: React.MouseEvent&lt;HTMLElement&gt;) =&gt; void;<br>}<br><br>const Icon = ({ name, className, size, onClick }: Props) =&gt; {<br>  console.log({ icons: icons[name], name });<br>  const icon = useMemo(() =&gt; {<br>    const isIconFromProvider = name in icons &amp;&amp; !name.includes(&quot;_local&quot;);<br><br>    if (isIconFromProvider) {<br>      const icon = icons[name as keyof typeof icons];<br>      return React.cloneElement(icon as React.ReactElement, {<br>        className,<br>        size,<br>        onClick,<br>      });<br>    }<br><br>    if (!isIconFromProvider) {<br>      return (<br>        &lt;NextImg<br>          onClick={onClick}<br>          src={icons[name]}<br>          alt={name}<br>          className={className}<br>          style={{ width: size, height: size }}<br>          width={size}<br>          height={size}<br>        /&gt;<br>      );<br>    }<br>    return &lt;&gt;&lt;/&gt;;<br>  }, [name, className, size, onClick]);<br><br>  return &lt;&gt;{icon}&lt;/&gt;;<br>};<br><br>export default Icon;</pre><p>You can define a centralized icon name mapping, making it simple to manage your icons. Then, you can simply import and use the icon in any component where it’s needed. This approach ensures consistency and makes updates or changes effortless.</p><pre> &lt;Icon name={&quot;plus&quot;} size={32} className={&quot;...&quot;}/&gt;</pre><p>Managing icons efficiently in a React application is crucial for ensuring consistency and simplifying updates. I hope this post provides you with valuable insights and inspires you to implement cleaner, more maintainable code in your React projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e9e7ae2c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nuxt 3: Effective managing Api]]></title>
            <link>https://medium.com/@tranphuocloc070699/nuxt-3-effective-managing-api-8ceb4003e91a?source=rss-92b3c40d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ceb4003e91a</guid>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Luke]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 23:48:43 GMT</pubDate>
            <atom:updated>2024-04-02T02:13:41.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKUahVHSFiCZmrtr3OBsiA.png" /><figcaption>Nuxt 3: Effective Managing Api</figcaption></figure><p>Have you ever messed up when trying to handle tons of API? Do you want to implement the best way to handle API? I did, and I spent so much time to find this dream. But today, I want to share with you my way. This is called the Repository Pattern, I hope you see it as an option to solve this problem.</p><p>Thanks to Vue Mastery and Luiz Eduardo Zappa, your article helped me so much.</p><p>Vue Mastery article: <a href="https://www.vuemastery.com/blog/api-management-in-nuxt-3-with-typescript/">API Management in Nuxt 3 with TypeScript</a></p><p>Luiz Eduardo Zappa article: <a href="https://medium.com/@luizzappa/nuxt-3-repository-pattern-organising-and-managing-your-calls-to-apis-with-typescript-acd563a4e046">Nuxt 3 | Repository pattern: organising and managing your calls to APIs (Typescript)</a></p><p>Link github repository:<strong> </strong><a href="https://github.com/tranphuocloc070699/nuxt-repository-pattern"><strong>nuxt-repository-pattern</strong></a></p><p>You can follow the article I mentioned above to understand what is repository pattern. I will show you how to implement it.</p><p>First of all. Let’s create a types folder to implement all data types that get from the server.</p><pre>mkdir types</pre><p>To make this article simple to follow, I just created two models, Post and User. In the real world, you need to create tons of models, so you can divide them into files for easier managing.</p><p><strong>types/model.ts</strong></p><pre>export interface IPost {<br>  userId: string;<br>  id: string;<br>  title: string;<br>  body: string;<br>}<br><br>export interface IUser {<br>  id: number;<br>  name: string;<br>  username: string;<br>  email: string;<br>  accessToken:string;<br>}</pre><p>Then create a repository folder.</p><pre>mkdir repository</pre><p>Create a factory.ts, this class is like a blueprint, any module (I will show later) will extend this class.</p><p><em>Note: you can add default headers in this class or custom any headers in the class that extend the Factory class.</em></p><p><strong>repository/factory.ts</strong></p><pre>import type {$Fetch, NitroFetchOptions} from &#39;nitropack&#39;<br><br>interface IHttpFactory {<br>  method: &#39;GET&#39; | &#39;HEAD&#39; | &#39;PATCH&#39; | &#39;POST&#39; | &#39;PUT&#39; | &#39;DELETE&#39; | &#39;CONNECT&#39; | &#39;OPTIONS&#39; | &#39;TRACE&#39; | &#39;get&#39; | &#39;head&#39; | &#39;patch&#39; | &#39;post&#39; | &#39;put&#39; | &#39;delete&#39; | &#39;connect&#39; | &#39;options&#39; | &#39;trace&#39;,<br>  url: string,<br>  fetchOptions?: NitroFetchOptions&lt;&#39;json&#39;&gt;,<br>  body?: object,<br>}<br><br>class HttpFactory {<br>  private readonly $fetch: $Fetch;<br><br>  constructor(fetch: $Fetch) {<br>    this.$fetch = fetch;<br>  }<br><br>  async call&lt;T&gt;({method, url, fetchOptions, body}: IHttpFactory): Promise&lt;T&gt; {<br>    return this.$fetch&lt;T&gt;(<br>        url,<br>        {<br>          method,<br>          body,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>          },<br>          ...fetchOptions,<br>        }<br>    )<br>  }<br>}<br>export default HttpFactory;</pre><p>I create a routes.client to handle API endpoint from server, /api for call to Nuxt server.</p><p><strong>repository/routes.client.ts</strong></p><pre>/*<br>* Prefix /api for api server<br>*/<br>const prefix : string = &#39;/api&#39;;<br><br>/*<br>* Prefix /api/another for another server<br>* */<br>const anotherPrefix : string = &#39;/api/another&#39;<br><br>const Routes = {<br>  Post:{<br>    FetchAll:()  =&gt; `${prefix}/posts`,<br>    FetchDetail : (id: number) =&gt; `${prefix}/posts/${id}`,<br>    CreatePost :()  =&gt; `${prefix}/posts`<br>  },<br>  User:{<br>    Authenticate:()  =&gt; `${anotherPrefix}/users`<br>  }<br>}<br><br>export default Routes</pre><p>Now let us create a modules folder, this folder inside repository folder and contains a repository for your model like user, post, …</p><pre>mkdir modules</pre><p>I will create two modules, user-module, and post-module, which correspond to user model and post model.</p><p><strong>repository/modules/post.module.ts</strong></p><pre>import FetchFactory from &quot;../factory&quot;;<br>import Routes from &quot;../routes.client&quot;;<br>import type {IPost} from &quot;~/types/model&quot;;<br><br>class PostModule extends FetchFactory {<br>  private readonly RESOURCE = Routes.Post;<br>  private accessToken: string = &#39;&#39;;<br><br>  async fetchAll() {<br>    return this.call&lt;IPost&gt;(<br>        {<br>          method: &#39;GET&#39;, url: `${this.RESOURCE.FetchAll()}`<br>        }<br>    )<br>  }<br><br>  async createPost(dto : IPost) {<br>    return this.call&lt;IPost&gt;(<br>        {<br>          method: &#39;POST&#39;, url: `${this.RESOURCE.CreatePost()}`,body:dto, fetchOptions: {<br>            headers: {<br>              ...(this.accessToken ? {<br>                &#39;Authorization&#39;: `Bearer ${this.accessToken}`<br>              } : {})<br>            },<br><br>          }<br>        }<br>    )<br>  }<br>  async fetchDetail(id : number) {<br>    return this.call&lt;IPost&gt;(<br>        {<br>          method: &#39;GET&#39;, url: `${this.RESOURCE.FetchDetail(id)}`, fetchOptions: {<br>            headers: {<br>              ...(this.accessToken ? {<br>                &#39;Authorization&#39;: `Bearer ${this.accessToken}`<br>              } : {})<br>            },<br><br>          }<br>        }<br>    )<br>  }<br><br>  setAccessToken(accessToken: string) {<br>    this.accessToken = accessToken;<br>  }<br>}<br><br>export default PostModule;</pre><p>You can see the setAccessToken function, this function authenticates the user and add the token server to headers.</p><p><strong>repository/modules/auth.module.ts</strong></p><pre>import FetchFactory from &quot;../factory&quot;;<br>import Routes from &quot;../routes.client&quot;;<br>import type { IUser} from &quot;~/types/model&quot;;<br><br>class AuthModule extends FetchFactory {<br>  private readonly RESOURCE = Routes.User;<br>  async authenticate() {<br>    return this.call&lt;IUser&gt;(<br>        {<br>          method: &#39;GET&#39;, url: `${this.RESOURCE.Authenticate()}`<br>        }<br>    )<br>  }<br>}<br><br>export default AuthModule;</pre><p>I just create an authenticate function to get token from server and add it to any endpoint that needs authenticate.</p><p>Then create a plugins folder, this folder manages plugins of Nuxt.</p><pre>mkdir plugins</pre><p>I will create a custom plugin, it helps us to access our repository.<br><strong>plugins/api.ts</strong></p><pre>import PostModule from &quot;~/repository/modules/post.module&quot;;<br>import AuthModule from &quot;~/repository/modules/auth.module&quot;;<br>export interface IApiInstance {<br>  post: PostModule;<br>  auth: AuthModule;<br>}<br><br>export default defineNuxtPlugin((nuxtApp) =&gt; {<br>  const config = useRuntimeConfig();<br>  const NUXT_BASE_URL_PROXY_SERVER : string = config.public.NUXT_BASE_URL_PROXY_SERVER;<br><br><br>  const apiFetcher = $fetch.create({<br>    baseURL: NUXT_BASE_URL_PROXY_SERVER,<br>    onRequest({ request, response }) {},<br>  });<br>  const postModule = new PostModule(apiFetcher);<br>  const authModule = new AuthModule(apiFetcher);<br><br>  const modules: IApiInstance = {<br>    post: postModule,<br>    auth: authModule,<br>  };<br>  /*<br>  * ! This code below is example for the case you want to authenticate user and set token to headers.<br>  * Why call api in process.client?<br>  * =&gt; Cookie only exist on client.<br>  *  */<br>  if (process.client) {<br>    modules.auth<br>    .authenticate()<br>    .then((data) =&gt; {<br>      if(data.accessToken){<br>        postModule.setAccessToken(data.accessToken);<br>      }<br>    })<br>    .catch((err: any) =&gt; {<br>      console.error(&quot;Error occur:&quot; + err)<br><br>    });<br>  }<br><br>  return {<br>    provide: {<br>      api: modules,<br>    },<br>  };<br>});</pre><p>so far so good, now we can access our repository by $api . Another notice is if you need cookie to authenticate , you need to put authenticate api on client, because Nuxt cannot get cookie on server.</p><p>The final step, we need to create a Nuxt server to handle request, in real world, we don’t want to expose server hostname, so Nuxt server as a proxy to hide server hostname. Isn’t that good?</p><p>When you create a Nuxt app by create-nuxt-app, it always create a server folder for you. So I just need to create routes.server.ts to handle requests.</p><p><strong>server/api/routes.server.ts</strong></p><pre>export const Routes = {<br>  another:{<br>    name:&#39;/api/another&#39;,<br>    regex:/^\/api\/another$/<br>  },<br>  core:{<br>    name:&#39;/api&#39;,<br>    regex:/^\/api\//<br>  }<br>}</pre><p>Then create a […].ts, this file handle all routes call to /api.</p><p><strong>server/api/[…].ts</strong></p><pre>import { joinURL } from &#39;ufo&#39;<br>import { Routes } from &#39;./routes.server&#39;<br><br>export default defineEventHandler(async (event) =&gt; {<br>  const coreUrl = useRuntimeConfig().NUXT_BASE_URL_JSON_PLACEHOLDER_SERVER<br>  const anotherUrl = useRuntimeConfig().NUXT_BASE_URL_ANOTHER_SERVER<br><br>  let path = &#39;&#39;<br>  let target = &#39;&#39;<br>  /*<br>  * Case: /api<br>  * */<br>  if(event.path.startsWith(Routes.core.name)){<br>    path = event.path.replace(Routes.core.name, &#39;&#39;)<br>    target = joinURL(coreUrl, path)<br>  }<br>  /*<br>  * Case: /api/another<br>  * */<br>  else if(event.path.startsWith(Routes.another.name)){<br>    path = event.path.replace(Routes.another.regex, &#39;&#39;)<br>    target = joinURL(anotherUrl, path)<br>  }<br><br>  return proxyRequest(event, target)<br>})</pre><p>Tada, it done. Let’s create a example to use my repository.</p><p><strong>stores/post.store.ts</strong></p><pre>import type {IPost} from &quot;~/types/model&quot;;<br><br>import {defineStore} from &quot;pinia&quot;;<br><br>export const usePostStore = defineStore(&quot;post&quot;, () =&gt; {<br>  const {$api} = useNuxtApp();<br>  const postList = ref&lt;IPost[]&gt;([]);<br><br>  const fetchPostList = async () =&gt; {<br>    try {<br>      $api.post.fetchAll().then(data =&gt; {<br>        console.log(data)<br>      }).catch(error =&gt; {<br>        console.error(error)<br>      })<br>    } catch (error) {<br>      console.error(&quot;fetchPostList error:&quot; + error);<br>    }<br>  };<br><br>  return {postList, fetchPostList};<br>});</pre><p>And use on component</p><pre>&lt;script setup lang=&quot;ts&quot;&gt;<br>import type {IPost} from &quot;~/types/model&quot;;<br>import {usePostStore} from &quot;~/stores/post.store&quot;;<br><br>const {$api} = useNuxtApp()<br>const postStore = usePostStore();<br><br>// const {data, error, pending} = useAsyncData(&#39;fetchPostList&#39;, () =&gt; $api.post.fetchAll())<br>useAsyncData(&quot;fetchPosts&quot;, () =&gt; postStore.fetchPostList())<br>const createPost = (dto: IPost) =&gt; {<br>  $api.post.createPost(dto).then(data =&gt; {<br>  }).<br>  catch((error =&gt; {<br>  }))<br>}<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>&lt;/template&gt;<br><br>&lt;style scoped&gt;<br>&lt;/style&gt;</pre><h3>Conclusion</h3><p>Thank you for reading my article. Your engagement is appreciated. I welcome your questions and ideas to improve and expand upon the topics discussed. Let’s continue this conversation together for further exploration and understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ceb4003e91a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>