<?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 Harry San Juan on Medium]]></title>
        <description><![CDATA[Stories by Harry San Juan on Medium]]></description>
        <link>https://medium.com/@harrysanjuan?source=rss-f6c119cd36d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qj8PijUbd-m-W9RbUvQo2g.jpeg</url>
            <title>Stories by Harry San Juan on Medium</title>
            <link>https://medium.com/@harrysanjuan?source=rss-f6c119cd36d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:46:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harrysanjuan/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[I learned how Flask-Login works with Flask-SQLAlchemy & Flask-RESTful so you wouldn’t have to.]]></title>
            <link>https://medium.com/@harrysanjuan/i-learned-how-flask-login-works-with-flask-sqlalchemy-flask-restful-so-you-wouldnt-have-to-7b52f4f3e07d?source=rss-f6c119cd36d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b52f4f3e07d</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[flask-sqlalchemy]]></category>
            <category><![CDATA[flask-login]]></category>
            <category><![CDATA[flask-restful]]></category>
            <category><![CDATA[flask-api]]></category>
            <dc:creator><![CDATA[Harry San Juan]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 06:39:06 GMT</pubDate>
            <atom:updated>2024-12-04T06:39:06.329Z</atom:updated>
            <content:encoded><![CDATA[<p>Flask-Login is like the backstage crew for your app’s user authentication — it handles the messy work of managing sessions and keeps the show running smoothly. If you’re using Flask-SQLAlchemy for database management and Flask-RESTful for APIs, Flask-Login fits right in, making it easier to add user login, logout, and session handling to your app.</p><h4>Here’s what Flask-Login does for you:</h4><p>• <strong>Session Management</strong>: It stores the active user’s ID in the Flask session, letting you easily log users in and out.</p><p>• <strong>Access Control</strong>: Provides the @login_required decorator, allowing you to restrict views to logged-in (or logged-out) users.</p><p>• <strong>“Remember Me”</strong>: Handles persistent login functionality, so users don’t have to log in every single time.</p><p>• <strong>Session Security</strong>: Helps protect against session theft by cookie hijackers.</p><h4>But here’s what it doesn’t do (which is great because it keeps things flexible):</h4><p>• <strong>Database-Agnostic</strong>: Flask-Login doesn’t impose a specific database or storage method — you’re free to choose how to load and manage users.</p><p>• <strong>Flexible Authentication</strong>: It doesn’t restrict you to a specific method like usernames and passwords. You can use OpenID, OAuth, or even magic links if you want.</p><p>• <strong>Permissions</strong>: It doesn’t handle fine-grained permissions beyond “logged in or not.”</p><p>• <strong>Account Management</strong>: Registration, password recovery, and other account workflows are entirely up to you.</p><p>With Flask-Login, you get just the right tools to manage authentication without being tied to a specific implementation, giving you the freedom to design your app the way you want. Let’s dive into how to integrate it with Flask-SQLAlchemy and Flask-RESTful to build a fully functional, secure API.</p><p><strong>Step 1: Install Flask-Login</strong></p><p>First things first: you need to install Flask-Login. You can do this with pip via the Terminal:</p><pre>pip install flask-login</pre><p>Once it’s installed, you’re good to start using it. Make sure to import it into your app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*Nz2opVLxMukzK_II746ATQ.png" /></figure><p><strong>Step 2: Initialize Flask-Login</strong></p><p>After creating your Flask app, you need to set up Flask-Login by creating an instance of the LoginManager and connecting it to your app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*xSLYc5ju60sWeM2tdCoi7g.png" /></figure><p>The secret_key is important because Flask uses it to securely sign your session cookies. The best strategy for generating a good one is using the os module from the command line:</p><pre>python -c &#39;import os; print(os.urandom(16))&#39;</pre><p><strong>Step 3: Create a User Model with Required Properties</strong></p><p>Flask-Login requires a user model that defines certain properties and methods to properly manage user sessions. If you’re using a database, this would typically be an ORM model (like a SQLAlchemy model). For simplicity, here’s a basic implementation of a user model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*C9HHZuAnxtkgvFaerz70Og.png" /></figure><p><strong>What Each Method Does</strong></p><p>1. get_id():</p><p>• This method must return a unique identifier for the user as a string. Flask-Login uses this to store the user ID in the session.</p><p>• Example: If your user model has an integer ID, you need to convert it to a string.</p><p>2. is_authenticated:</p><p>• A property that indicates whether the user has been successfully authenticated. Flask-Login relies on this to determine if the user is logged in.</p><p>3. is_active:</p><p>• A property that checks whether the user account is active. You can use this to disable accounts (e.g., by storing a flag in the database). For most applications, you’ll return True by default unless there’s a specific reason to deactivate accounts.</p><p>4. is_anonymous:</p><ul><li>A property that returns True if the user is not logged in. Since this property is for anonymous users, your actual user model should always return False.</li></ul><p><strong>Alternatively, you can simplify by utilizing UserMixin</strong></p><p>The UserMixin class from Flask-Login provides default implementations for these properties and the get_id() method. By inheriting UserMixin, you save yourself the trouble of writing these manually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*iy-PMmjLqizTo8KKLJ7Qog.png" /></figure><p>The UserMixin implementation works for most use cases, but if you need custom behavior (e.g., inactive users), you can override any of the properties.</p><p><strong>Step 4: Define a User Loader</strong></p><p>Flask-Login needs to know how to load users based on their ID, which is stored in the session. You define this with the @login_manager.user_loader decorator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*S3RBlVnd7Iu8fByK8MvH-w.png" /></figure><p><strong>Step 5: Building Login and Logout Endpoints with Flask-RESTful</strong></p><p>Now that we have a user model and session management, let’s create login and logout endpoints using Flask-RESTful.</p><p><strong>Login Endpoint:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*vdk1I6ba0iTan0U3v3NBeA.png" /></figure><p><strong>Logout Endpoint:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*hSBGrMmqCqIG6UpoGVSZqA.png" /></figure><p><strong>What’s Happening</strong>:</p><ul><li>login_user(user): Logs the user in and starts their session.</li><li>Notice the optional second argument to login_user. Setting `remember` to True will keep the user authenticated even after the user closes the app!</li><li>logout_user(): Ends the user’s session and clears their data from Flask-Login’s memory.</li><li>We placed the @login_required decorator provided by Flask-Login as we only want authenticated users to have access to this resource. If the user isn’t logged in, Flask-Login automatically redirects them to a login page (you can customize this behavior with login_manager.login_view). Makes sense, right?</li></ul><p><strong>Step 6: Using current_user to Identify the Authenticated User</strong></p><p>Flask-Login provides a very handy global object called current_user. This object gives you access to the user currently logged into the application. It’s like your app’s way of saying, “Hey, I know who this is!” Whether you’re building a frontend or an API, current_user becomes a powerful tool for managing authenticated user data.</p><p><strong>How current_user Works</strong></p><p>The current_user object is dynamically loaded by Flask-Login based on the user ID stored in the session. It acts as an instance of your user model (or a subclass of AnonymousUserMixin if no user is logged in). This means you can call any of the properties or methods defined on your user model directly from current_user.</p><p>When working with Flask-RESTful, you can use current_user inside your resource methods just like in a regular Flask route. For instance, let’s create a resource to return the authenticated user’s details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*LCxKfgxl_9duTxvPT9D84w.png" /><figcaption>We’re able to call to_dict() on current_user since it’s an instance of the User model that inherits from SerializerMixin!</figcaption></figure><p>This allows your frontend to fetch the authenticated user’s profile by simply hitting the /current_user endpoint. And that’s pretty much it!</p><p>With Flask-Login, Flask-SQLAlchemy, and Flask-RESTful working together, you now have a secure, session-managed API for your application. Whether you’re building a simple app or a large-scale project, this trio has you covered. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b52f4f3e07d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering CRUD with Flask-SQLAlchemy: A Practical Guide]]></title>
            <link>https://medium.com/@harrysanjuan/mastering-crud-with-flask-sqlalchemy-a-practical-guide-6c90102c2d15?source=rss-f6c119cd36d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c90102c2d15</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[querying]]></category>
            <category><![CDATA[flask-sqlalchemy]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <dc:creator><![CDATA[Harry San Juan]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 05:38:02 GMT</pubDate>
            <atom:updated>2024-10-31T05:38:02.149Z</atom:updated>
            <content:encoded><![CDATA[<p>Flask-SQLAlchemy is a fantastic tool for handling databases in Flask, offering a seamless way to map Python classes to database tables and manage data without needing to write raw SQL. In this guide, we’re going to take a deep dive into CRUD operations — Create, Read, Update, Delete — and explore the core functions that make them happen: <strong><em>db.session</em></strong>, <strong><em>add()</em></strong>, <strong><em>commit()</em></strong>, <strong><em>query()</em></strong>, <strong><em>filter()</em></strong>, as well as advanced features like <strong><em>get()</em></strong>, <strong><em>order_by()</em></strong>, <strong><em>update()</em></strong>, and <strong><em>delete()</em></strong>. By the end, you’ll be fluent in performing queries in Flask-SQLAlchemy!</p><p><strong>Setting Up Flask-SQLAlchemy</strong></p><p>Before we get to the good stuff, let’s set up a Flask app with SQLAlchemy:</p><pre>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br><br>app = Flask(__name__)<br>app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;sqlite:///example.db&#39;<br>db = SQLAlchemy(app)</pre><p><strong>Defining a Model</strong></p><p>Let’s start with a simple User model. This table will hold our users’ id, username, and email.</p><pre>class User(db.Model):<br>    __tablename__ = &#39;users&#39;<br>    <br>    id = db.Column(db.Integer, primary_key=True)<br>    username = db.Column(db.String(80), unique=True, nullable=False)<br>    email = db.Column(db.String(120), unique=True, nullable=False)<br>    <br>    def __repr__(self):<br>        return f&#39;&lt;User {self.username}&gt;&#39;</pre><p>With this User model in place, let’s look at how to create, retrieve, update, and delete records.</p><p><strong>Create: Adding Records</strong></p><p>Adding records in Flask-SQLAlchemy is simple, but understanding what’s happening under the hood with <em>db.session</em> is worth the time.</p><pre>new_user = User(username=&quot;john_doe&quot;, email=&quot;john@example.com&quot;)<br>db.session.add(new_user)<br>db.session.commit()</pre><p>Here’s what’s happening:</p><p>•<em> db.session.add(new_user)</em>: This adds the new_user instance to the session, which prepares it for insertion.</p><p>• <em>db.session.commit()</em>: Commits the transaction, making our new record permanent in the database.</p><blockquote><strong>Tip:</strong> You can add multiple records at once using <strong>add_all()</strong> which accepts a list!</blockquote><p><strong>Read: Querying Records with <em>query</em>, <em>filter()</em>, and <em>filter_by()</em></strong></p><p><strong>Basic Queries with query</strong></p><p>Fetching data from the database is straightforward with SQLAlchemy’s <em>query() </em>method:</p><pre>users = User.query.all()<br>for user in users:<br>    print(user)</pre><p><em>users</em> will evaluate into a list of all instances of the User class that you can iterate through!</p><p><strong>Filtering with <em>filter() </em>and <em>filter_by()</em></strong></p><p><em>filter() </em>and <em>filter_by()</em> allow us to be selective about the data we retrieve.</p><pre>User.query.filter(User.id === 2).first()</pre><p>The above function will filter rows for a User instance with an <em>id</em> of 2.</p><p>When the query is simple, <em>filter_by()</em> makes it even easier:</p><pre>user = User.query.filter_by(username=&quot;john_doe&quot;).first()</pre><blockquote><strong>Quick Tip:</strong> first() gets the first match or returns None if nothing is found. all() returns all matches, and count() gives the total.</blockquote><p><strong>Fast Primary Key Lookups with <em>get()</em></strong></p><p>If you know the primary key, <em>get()</em> is the fastest way to find a specific record:</p><pre>user = User.query.get(1)</pre><p>This bypasses some query-building overhead, making it faster for primary key lookups.</p><p><strong>Ordering Results with <em>order_by()</em></strong></p><p>To sort data, order_by does the trick:</p><pre>users = User.query.order_by(&#39;username&#39;).all()</pre><p>Here, our users are sorted alphabetically by username.</p><p>To update a record, load it, change the values, and call <em>commit() </em>to save:</p><pre># Update a user’s email<br>user = User.query.filter_by(username=&quot;john_doe&quot;).first()<br>user.email = &quot;john_doe_updated@example.com&quot;<br>db.session.commit()</pre><p>Want to update multiple records? update() on a query can be really efficient:</p><pre># Change email domain for all users<br>User.query.filter(User.email.like(&#39;%@example.com&#39;)).update({&#39;email&#39;: &#39;new_email@example.com&#39;})<br>db.session.commit()</pre><p><strong>Delete: Removing Records</strong></p><p>Deleting records follows a similar pattern to updating, but we use delete():</p><pre>user = User.query.filter_by(username=&quot;john_doe&quot;).first()<br>db.session.delete(user)<br>db.session.commit()</pre><p>Or, for batch deletions:</p><pre># Delete all users with a specific email domain<br>User.query.filter(User.email.like(&#39;%@example.com&#39;)).delete()<br>db.session.commit()</pre><p>Deleting a record removes it from the database immediately after commit().</p><p><strong>Transactions and Rollbacks</strong></p><p>Transactions are vital for keeping data consistent. If something fails partway through, we can roll back the session, undoing all pending changes.</p><pre>try:<br>    new_user = User(username=&quot;duplicate_user&quot;, email=&quot;duplicate@example.com&quot;)<br>    db.session.add(new_user)<br>    db.session.commit()<br>except Exception as e:<br>    db.session.rollback()<br>    print(&quot;Error occurred:&quot;, e)</pre><p>Here, if an error occurs (like a constraint violation), <em>rollback() </em>reverts any pending changes.</p><p><strong>Wrapping Up</strong></p><p>Flask-SQLAlchemy provides everything needed to handle database interactions effectively. Here’s a quick rundown:</p><p>• <strong>Create</strong>: Use <em>add()</em> and <em>commit()</em> for new records.</p><p>• <strong>Read</strong>: Retrieve data with <em>query()</em>, <em>filter()</em>, <em>filter_by()</em>, and <em>get()</em>.</p><p>• <strong>Update</strong>: Modify records with direct assignments or <em>update()</em>.</p><p>• <strong>Delete</strong>: Use <em>delete()</em> to remove records.</p><p>Flask-SQLAlchemy lets us handle these operations with ease, empowering you to build powerful, data-driven applications with minimal code. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c90102c2d15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Magic of Python List Comprehensions: A Deep Dive into Elegant Code]]></title>
            <link>https://medium.com/@harrysanjuan/unlocking-the-magic-of-python-list-comprehensions-a-deep-dive-into-elegant-code-4cb4308db60f?source=rss-f6c119cd36d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cb4308db60f</guid>
            <category><![CDATA[python-list-comprehension]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[list-comprehension]]></category>
            <dc:creator><![CDATA[Harry San Juan]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 04:15:20 GMT</pubDate>
            <atom:updated>2024-06-11T04:15:20.341Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever wished your code could be more concise, elegant, and just plain fun to write? Enter list comprehensions — one of Python’s most magical features! List comprehensions let you create lists in a single line of code, making your life easier and your code more readable. Let’s dive deep into the world of list comprehensions, uncover their history, explore their myriad applications, and even peek at their relatives like dictionary and set comprehensions.</p><h3>The History of List Comprehensions</h3><p>List comprehensions were introduced to Python in version 2.0, released on October 16, 2000. Inspired by similar constructs in languages like Haskell and SETL, list comprehensions brought a breath of functional programming air to Python. The goal? To make your code more syntactically appealing and efficient.</p><h3>What is a List Comprehension?</h3><p>A list comprehension is a syntactic sugar that lets you generate lists in a clean and concise way. Think of it as a magical recipe: brackets, an expression, a for clause, and — voilà! — you have a list. Let’s see how this works in practice.</p><h3>Transforming Traditional For-Loops into List Comprehensions</h3><p>Imagine you need a list of squares of numbers from 0 to 9. Using a traditional for-loop, you’d write:</p><pre>squares = []<br>for x in range(10):<br>    squares.append(x ** 2)<br>print(squares)</pre><p>Not bad, but what if we could wave our magic wand and simplify this? With list comprehensions:</p><pre>squares = [x ** 2 for x in range(10)]<br>print(squares)</pre><p>See how concise and readable that is?</p><h3>Applications of List Comprehensions</h3><p>List comprehensions are incredibly versatile. Let’s explore some cool tricks:</p><h4>1. Filtering with List Comprehensions</h4><p>Want a list of even numbers from 0 to 9? Watch this:</p><p><em>Using a for-loop:</em></p><pre>evens = []<br>for x in range(10):<br>    if x % 2 == 0:<br>        evens.append(x)<br>print(evens)</pre><p><em>Using a list comprehension:</em></p><pre>evens = [x for x in range(10) if x % 2 == 0]<br>print(evens)</pre><h4>2. Transforming Elements</h4><p>Let’s turn some fruits to uppercase:</p><p><em>Using a for-loop:</em></p><pre>fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;cherry&#39;]<br>upper_fruits = []<br>for fruit in fruits:<br>    upper_fruits.append(fruit.upper())<br>print(upper_fruits)</pre><p><em>Using a list comprehension:</em></p><pre>fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;cherry&#39;]<br>upper_fruits = [fruit.upper() for fruit in fruits]<br>print(upper_fruits)</pre><h4>3. Nested Loops</h4><p>Create a list of tuples for a Cartesian product of colors and sizes:</p><p><em>Using nested for-loops:</em></p><pre>colors = [&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;]<br>sizes = [&#39;S&#39;, &#39;M&#39;, &#39;L&#39;]<br>cartesian_product = []<br>for color in colors:<br>    for size in sizes:<br>        cartesian_product.append((color, size))<br>print(cartesian_product)</pre><p><em>Using a nested list comprehension:</em></p><pre>colors = [&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;]<br>sizes = [&#39;S&#39;, &#39;M&#39;, &#39;L&#39;]<br>cartesian_product = [(color, size) for color in colors for size in sizes]<br>print(cartesian_product)</pre><h3>Crafting the Perfect List Comprehension</h3><p>Constructing list comprehensions can feel like casting a spell. Here’s the incantation:</p><ol><li><strong>Start with the expression you want to evaluate</strong>: This goes at the beginning.</li><li><strong>Add the for clause</strong>: Specify the iterable and the variable to represent each element.</li><li><strong>Include any conditions (optional)</strong>: Add an if clause to filter elements.</li></ol><p>The magic formula:</p><pre>[expression for item in iterable if condition]</pre><h4>Example Breakdown</h4><p>Let’s breakdown a spell for creating a list of squares for even numbers from 0 to 9:</p><ol><li><strong>Expression</strong>: x ** 2 (the square of each number)</li><li><strong>For clause</strong>: for x in range(10)</li><li><strong>Condition</strong>: if x % 2 == 0 (only even numbers)</li></ol><p>Combine them into a list comprehension:</p><pre>squares_of_evens = [x ** 2 for x in range(10) if x % 2 == 0]<br>print(squares_of_evens)</pre><h3>Beyond Lists: Pythonic Comprehensions</h3><p>Python isn’t just about lists. It has dictionary comprehensions, set comprehensions, and even generator expressions. Let’s meet the family:</p><h4>Dictionary Comprehensions</h4><p>Create dictionaries with the same elegance as lists:</p><p><em>Example:</em></p><pre>squares = {x: x ** 2 for x in range(10)}<br>print(squares)</pre><h4>Set Comprehensions</h4><p>Build sets with similar flair:</p><p><em>Example:</em></p><pre>unique_squares = {x ** 2 for x in range(10)}<br>print(unique_squares)</pre><h4>Generator Expressions</h4><p>Generator expressions are like list comprehensions but with parentheses. Generator expressions save the code to create new, complete lists which saves on memory:</p><p><em>Example:</em></p><pre>squares_generator = (x ** 2 for x in range(10))<br>for square in squares_generator:<br>    print(square)</pre><h3>Notable and Interesting Tidbits</h3><ul><li><strong>Performance Boost</strong>: List comprehensions are often faster than for-loops because they are optimized for the Python interpreter.</li><li><strong>Functional Programming</strong>: Inspired by functional programming, list comprehensions make your code more expressive and declarative.</li><li><strong>Readability</strong>: While concise, avoid overcomplicating comprehensions. If they get too complex, a traditional loop might be clearer.</li></ul><h3>Common Pitfalls and Tips</h3><ul><li><strong>Readability</strong>: Keep comprehensions simple and readable.</li><li><strong>Nested comprehensions</strong>: Use sparingly; consider breaking them into separate steps.</li><li><strong>Side effects</strong>: Use list comprehensions for creating lists, not for actions with side effects.</li></ul><h3>Practice Makes Perfect</h3><p>Get comfy with list comprehensions through practice. Start simple and gradually tackle more complex problems. Remember the structure and break down each part to ensure clarity.</p><h3>Conclusion</h3><p>List comprehensions are a magical feature in Python that can transform your code into something more concise, readable, and fun to write. By understanding and practicing their construction, you’ll master the art of writing elegant and efficient Python code. And don’t forget to explore other Pythonic comprehensions like dictionaries, sets, and generators. Happy coding, and may your code be ever Pythonic!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cb4308db60f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Controlled Inputs in React: A Comprehensive Guide]]></title>
            <link>https://medium.com/@harrysanjuan/mastering-controlled-inputs-in-react-a-comprehensive-guide-605779a5ce60?source=rss-f6c119cd36d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/605779a5ce60</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[controlled-input]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Harry San Juan]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 04:49:06 GMT</pubDate>
            <atom:updated>2024-03-19T04:49:06.176Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of web development, React has emerged as a dominant force, providing developers with powerful tools to build dynamic and interactive user interfaces. One fundamental aspect of React development is managing form inputs effectively. Controlled inputs play a crucial role in this process, offering developers precise control over form data. In this comprehensive guide, we’ll delve deep into controlled inputs in React, exploring what they are, why they’re important, and how to implement them effectively.</p><h3>Understanding Controlled Inputs</h3><p>Controlled inputs in React are input elements whose value is controlled by React’s state. Unlike traditional HTML inputs, where the value is managed by the DOM itself, controlled inputs delegate control to React components. This means that the value of the input is bound to a piece of state and updated via React’s setState() method.</p><h3>Why Use Controlled Inputs?</h3><p>Controlled inputs offer several advantages over uncontrolled inputs:</p><ol><li>Single Source of Truth: With controlled inputs, the value of the input field is always synced with React’s state. This ensures that there’s a single source of truth for the input value, making it easier to manage and manipulate.</li><li>Dynamic Updates: Since the input value is controlled by React’s state, developers have full control over when and how the input value changes. This allows for dynamic updates and validations based on user interactions or other application logic.</li><li>Easy Testing: Testing controlled inputs is simpler compared to uncontrolled inputs since their behavior is entirely deterministic. Developers can easily simulate user interactions and verify the expected behavior of the component.</li></ol><h3>Implementing Controlled Inputs</h3><p>Let’s dive into the practical implementation of controlled inputs in React in 3 simple steps:</p><h3>1. Setting Up State</h3><p>The first step is to define state variables to hold the values of your input fields. This is typically done by importing React’s useState() hook and defining your state variable using <strong>destructuring</strong> so you can access the variable and its setter function.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Form({ onAddCountry }) {<br>const [form, setForm] = useState({<br>    country: &quot;&quot;,<br>    date: &quot;&quot;,<br>    capital: &quot;&quot;,<br>    flagImage: &quot;&quot;,<br>    favorite: false,<br>    diaryEntry: &quot;&quot;<br>})<br><br>return (<br>    &lt;div className=&quot;new-country-form&quot;&gt;<br>      &lt;h2&gt;Post New Country&lt;/h2&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;div className=&quot;form-input&quot;&gt;<br>        &lt;input <br>        type=&quot;text&quot; <br>        name=&quot;country&quot; <br>        placeholder=&quot;Country&quot;<br>        value={form.country}<br>        onChange={handleChange} <br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><blockquote>In this example, form is the state variable holding the value of the input field, and setForm is the function to update that state. The state variable here is actually an Object with several key/value pairs.</blockquote><h3>2. Binding Input Value to State</h3><p>Finally, we bind the value of the input element to the state variable we defined earlier. This establishes the connection between the input field and React’s state, creating a controlled input!</p><pre>&lt;input <br>  type=&quot;text&quot; <br>  name=&quot;country&quot; <br>  placeholder=&quot;Country&quot;<br>  value={form.country}<br>  onChange={handleChange} <br> /&gt;</pre><blockquote>In this example, the input’s value is connected to the specific key of the form (in this case, <em>form.country</em>).</blockquote><h3>3. Handling Input Changes</h3><p>Next, we define an event handler function to update the state whenever the input value changes. This function is passed to the onChange event of the input element.</p><pre>function handleChange(e) {<br>    const key = e.target.name<br>    const value = e.target.type === &quot;checkbox&quot; ? e.target.checked : e.target.value<br>    setForm({<br>        ...form,<br>        [key]: value<br>    })<br>}</pre><blockquote>Here we are defining a <em>key</em> variable and a <em>value</em> variable that corresponds to the input’s name and value respectively. We are using a ternary expression to dynamically make sure we are using the right value depending on the input type being a checkbox or not. We then invoke <em>setForm</em> wherein we use a spread operator on the form to make a shallow copy of the current state variable’s value and edit the corresponding key with its corresponding value — effectively updating state!</blockquote><h3>Advanced Techniques</h3><p>Controlled inputs offer plenty of flexibility, and there are several advanced techniques you can employ to enhance their functionality:</p><ol><li><strong>Validation &amp;Error Handling</strong>: You can implement validation logic within the input change handler to enforce constraints on the input data and provide feedback to the user.</li><li><strong>Conditional Rendering</strong>: Based on the input value or other application state, you can conditionally render additional UI elements or alter the appearance of the input field.</li><li><strong>Custom Input Components</strong>: For complex input requirements, you can create custom input components that encapsulate the logic for managing the input state and provide a clean interface for other components to use.</li></ol><h3>Conclusion</h3><p>Controlled inputs are a fundamental concept in React development, offering a powerful mechanism for managing form data. By leveraging React’s state management capabilities, developers can create dynamic and interactive user interfaces with ease. Mastering controlled inputs opens up a world of possibilities for building robust and user-friendly web applications.</p><p>In this guide, we’ve covered the basics of controlled inputs, including their benefits, implementation, and advanced techniques. Armed with this knowledge, you’re well-equipped to tackle complex form handling scenarios in your React applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=605779a5ce60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing the Power of .fetch() Method and DOM Manipulation for Web Development Mastery]]></title>
            <link>https://medium.com/@harrysanjuan/unleashing-the-power-of-fetch-method-and-dom-manipulation-for-web-development-mastery-f0d27d484d17?source=rss-f6c119cd36d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0d27d484d17</guid>
            <category><![CDATA[dom-manipulation]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[flatiron-school]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Harry San Juan]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 07:16:28 GMT</pubDate>
            <atom:updated>2023-12-27T07:16:28.695Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unleashing the Power of .fetch() Method and DOM Manipulation for Web Development Mastery</h3><p>Web development is a constantly evolving landscape, with developers continually seeking innovative ways to create engaging and interactive user experiences. In this comprehensive exploration, we will delve into the intricacies of the powerful .fetch() method and its seamless integration with DOM manipulation. Furthermore, we will unravel the art of enhancing user interactivity by implementing event listeners through a hands-on example, showcasing the versatility and power of modern JavaScript.</p><h3>The Versatility of the .fetch() Method</h3><p>At the heart of modern web development lies the .fetch() method, a crucial tool for making HTTP requests in JavaScript. It operates asynchronously, allowing developers to initiate requests and handle responses more efficiently. Let&#39;s take a closer look at the code snippet:</p><pre>document.addEventListener(&#39;DOMContentLoaded&#39;, fetchDrinks);<br><br>function fetchDrinks() {<br>    const drinkUrl = &#39;https://www.thecocktaildb.com/api/json/v1/1/search.php?s=cocktail&#39;;<br>    fetch(drinkUrl)<br>        .then(res =&gt; res.json())<br>        .then(cocktails =&gt; {<br>            cocktails.drinks.forEach(drink =&gt; renderDrinks(drink))<br>        });<br>}</pre><p>In this snippet, we leverage the event listener for the DOMContentLoaded event to ensure that our code executes only when the entire DOM has loaded. Through the fetchDrinks function, the .fetch() method is then utilized to initiate a GET request to the Cocktail DB API. The response — which comes in the form of JSON — will then be parsed into a JavaScript object via the .json() method. Only after this can we begin to work with the data returned by our GET request. We then iterate through the drinks using the .forEach() method, calling the renderDrinks function for each iteration.</p><h3>Crafting Dynamic Content with DOM Manipulation</h3><p>The renderDrinks function is the cornerstone of dynamically rendering drinks to the DOM. Let&#39;s dissect the key components of this crucial function:</p><pre>function renderDrinks(drink) {<br>    const drinkContainer = document.querySelector(&#39;#drink_container&#39;);<br>    const span = document.createElement(&#39;span&#39;);<br>    span.innerText = drink.strDrink;<br>    drinkContainer.appendChild(span);<br><br>    span.addEventListener(&#39;click&#39;,...<br>}</pre><p>This code snippet showcases the creation of a new HTML span element for each drink, dynamically populating the drink_container div with the drink names. However, the true magic unfolds when a user interacts with a specific drink via a click event:</p><pre>span.addEventListener(&#39;click&#39;, () =&gt; {<br>    const drinkInfo = document.querySelector(&#39;#drink_info&#39;);    <br>    const img = document.createElement(&#39;img&#39;);<br>    const h2 = document.createElement(&#39;h2&#39;);<br>    const ingredient= document.createElement(&#39;h4&#39;);<br>    const p = document.createElement(&#39;p&#39;);<br>    const button = document.createElement(&#39;button&#39;);<br>    <br>    h2.innerText = drink.strDrink;<br>    img.src = drink.strDrinkThumb;<br>    ingredient.innerText = &#39;Ingredients:&#39;;<br>    p.innerText = drink.strInstructions;<br>    button.innerText = &#39;Change Language to German 🇩🇪&#39;; <br>    <br>    drinkInfo.append(h2, img, ingredient);<br>});</pre><p>Upon clicking a drink, the renderDrinks function orchestrates the dynamic population of the drink_info, ingredients, and instructions divs with relevant data from the API call, elevating the user experience to a new level.</p><h3>Elevating User Interaction Through Event Listeners</h3><p>One hallmark of interactive web applications is the sensible use of event listeners. The provided code exemplifies this through a language-switching feature, showcasing the dynamic nature of user interaction:</p><pre>button.addEventListener(&#39;click&#39;, () =&gt; {<br>    if (p.innerText === drink.strInstructions) {<br>        p.innerText = drink.strInstructionsDE;<br>        button.innerText = &#39;Change Language to Italian 🇮🇹&#39;;  <br>    } else if (p.innerText === drink.strInstructionsDE) {<br>        p.innerText = drink.strInstructionsIT;<br>        button.innerText = &#39;Change Language to English 🇬🇧&#39;;<br>    } else if (p.innerText === drink.strInstructionsIT) {<br>        p.innerText = drink.strInstructions;<br>        button.innerText = &#39;Change Language to German 🇩🇪&#39;;<br>    }<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*A2tFJX0MaEBvSiKOVcru7A.gif" /><figcaption>renderDrinks function at work</figcaption></figure><p>This captivating feature allows users to seamlessly toggle between different language versions of the drink instructions with a simple button click. The dynamic content alteration based on user actions is a testament to the potential of event listeners in creating engaging user experiences.</p><h3>Expanding Beyond the Code</h3><p>As we navigate the realms of web development, it’s essential to recognize that expertise extends beyond writing mere code. Consideration of user accessibility, performance optimization, and user experience design are essential facets of building robust and user-friendly web applications.</p><h3>Conclusion</h3><p>A profound understanding of the .fetch() method, along with adept DOM manipulation and strategic use of event listeners, empowers us developers to craft dynamic and immersive web applications. The exemplified code not only demonstrates the synergy between data fetching, rendering, and interactivity but also provides a foundation for building robust and user-friendly web experiences.</p><p>As you embark on your web development journey, these concepts will undoubtedly propel your skills to new heights, enabling you to create compelling and responsive applications. The path to mastery lies not only in the code you write but in the comprehensive approach you take towards creating a seamless and delightful user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0d27d484d17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>