<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: hyunho98</title>
    <description>The latest articles on DEV Community by hyunho98 (@hyunho98).</description>
    <link>https://dev.to/hyunho98</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1002503%2F4e31d406-0589-4fa5-bc08-ad4fef34d468.jpeg</url>
      <title>DEV Community: hyunho98</title>
      <link>https://dev.to/hyunho98</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/hyunho98"/>
    <language>en</language>
    <item>
      <title>Utilizing Delegated Types to Manage Multiple Types of Users</title>
      <dc:creator>hyunho98</dc:creator>
      <pubDate>Tue, 19 Dec 2023 23:39:31 +0000</pubDate>
      <link>https://dev.to/hyunho98/utilizing-delegated-types-to-manage-multiple-types-of-users-52da</link>
      <guid>https://dev.to/hyunho98/utilizing-delegated-types-to-manage-multiple-types-of-users-52da</guid>
      <description>&lt;p&gt;In ActiveRecord, the Delegated Types approach is used to simultaneously interface with two tables with separate attributes. The Delegated Types &lt;a href="https://api.rubyonrails.org/classes/ActiveRecord/DelegatedType.html"&gt;documentation page&lt;/a&gt; poses that "pagination", or the grouping and division of code blocks, of two different tables was not possible before the inclusion of delegated types because the attributes of an instance of a superclass and its subclasses can only persist within their respective tables. Because of this, there's no way for us to easily retrieve and organize instances of subclasses without multiple queries. The addition of another subclass would only complicate this process further. Delegated types streamlines this process by allowing the superclass to share its attributes with any of its subclasses.&lt;/p&gt;

&lt;h2&gt;
  
  
  Practical Usage
&lt;/h2&gt;

&lt;p&gt;Using my project &lt;a href="https://github.com/hyunho98/ad-space"&gt;AdSpace&lt;/a&gt; as an example, one way we can use delegated types is to implement different kinds of Users. In AdSpace, there are two kinds of Users. One of these is a Company that can create advertisements for a product that the other user type, the Advertiser, can then claim and run in their specific advertising market.&lt;/p&gt;

&lt;h3&gt;
  
  
  Initial Setup
&lt;/h3&gt;

&lt;p&gt;Since the superclass in this case is the User, we implement delegated types in the User class file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/models/user.rb

class User &amp;lt; ApplicationRecord
    delegated_type :userable, types: %w[ Agency Company ], dependent: :destroy
    ...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this one line, we declare the delegated type as userable, which then accepts the different kinds of Users as an array of strings. Dependent destroy can also be added to also destroy any Agency or Company instances that are attached to a User instance that is destroyed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/models/userable.rb

module Userable
    extend ActiveSupport::Concern

    included do
        has_one :user, as: :userable, touch: true
        accepts_nested_attributes_for :user
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We then create the Userable concern that, when included in our&lt;br&gt;
company.rb and agency.rb files, establishes a has_one relationship with our User class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# db/schema.rb

create_table "users", force: :cascade do |t|
  t.string "username"
  t.string "password_digest"
  t.string "userable_type"
  t.integer "userable_id"
  ...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last thing we need to do is include userable type and id columns to our users table. These are used by delegated types to pull our user type by its type and id (eg. "Company", Company.id of 1)&lt;/p&gt;

&lt;p&gt;NOTE: In AdSpace, the attribute "username" is given to the superclass so it can be validated as present and unique across all users while an attribute like "name" is given to the user types so they can be validated and compared amongst other instances of the subclass (An Agency and Company can both be  named "brown_cow" but two Companies can't both be named "how_now".) &lt;/p&gt;

&lt;h3&gt;
  
  
  Controller Actions
&lt;/h3&gt;

&lt;p&gt;Since we've established Companies and Agencies as different types of Users, we can handle any generic or shared controller actions in the Users Controller.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/controllers/users_controller.rb

def create
    company_agency = params.has_key?(:industry) ? (
        Company.new(company_params)
    ) : (
        Agency.new(agency_params)
    )

    user = User.create!({**user_params, userable: company_agency})
    session[:user_id] = user.id
    session[:user_type] = user.userable_type
    render json: user.userable, status: :created
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our create action, we create an instance of the userable depending on the received parameters (NOTE: If we add more user types, we could receive a "type" parameter and create a new type using a switch statement instead of a ternary operator.)&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Entry.create! entryable: Comment.new(content: "Hello!")&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The documentation uses this example to create a new record with a delegator and delegatee at the same time but I had difficulty implementing it in this way in the controller.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;user = User.create!({**user_params, userable: company_agency})&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I found that with strong params, using the splat operator (**) along with the userable attribute allows me to create, save, and validate the User instance in one line. This comes with the added bonus of also saving and validating company_agency.&lt;/p&gt;

&lt;p&gt;We then save the user's id and the userable's type in the sessions hash to be used in other backend actions. Since we want to keep attributes like the password digest from being passed back into the front end, we only need to render the userable. NOTE: In AdSpace, I've opted to send back some User attributes like the username, user id, and userable_type to the frontend to filter or change views depending on the type of user (An Agency cannot reach the Ad creation page.)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/controllers/users_controller.rb

def show
    user = User.find(session[:user_id]).userable
    render json: user
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our backend, we can now query for and find a user based on the user_id stored in our sessions hash. If we wanted to search for a User amongst all Companies or Agencies without delegated types we would have to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Add additional validations to make sure a Company and Agency don't share the same login credentials&lt;/li&gt;
&lt;li&gt;Find a way for the front end to communicate to the backend what kind of User to look for (Open to user error)&lt;/li&gt;
&lt;li&gt;Query through all Companies or Agencies for a match
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/controllers/application_controller.rb

class ApplicationController &amp;lt; ActionController::API
    ...
    private
    ...
    def company_only
        render json: { errors: ["You must be a company to do this"] }, status: :unauthorized unless session[:user_type] == "Company"
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we can get the user's type from the userable_type column in the User's table, it is also easier to limit controller actions to the company.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/controllers/ads_controller.rb

class AdsController &amp;lt; ApplicationController
    before_action :company_only, only: [:create, :destroy]
    ...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can add a before_action line to limit the creation and destruction of ads to a Users with a userable_type of "Company." This way of using delegated_types to distinguish User type in the backend is much more elegant than the alternative of storing an attribute of the Company in the sessions hash and then running it through an if or case statement. And this is only one of the many ways we save space in our code.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Rest of the Code
&lt;/h3&gt;

&lt;p&gt;The inclusion of Delegated Types assists us in cleaning up our code and establishing a separation of concerns in the backend and frontend. It saves us from having to write out CRUD actions for each type of User and keeps our logic in one place by limiting the required amount and complexity of fetch requests. Thanks to this, we can more easily build on top of our code using the existing framework.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Rails and ActiveRecord: Errors Save Lives</title>
      <dc:creator>hyunho98</dc:creator>
      <pubDate>Sat, 11 Nov 2023 02:11:24 +0000</pubDate>
      <link>https://dev.to/hyunho98/rails-and-activerecord-errors-save-lives-516k</link>
      <guid>https://dev.to/hyunho98/rails-and-activerecord-errors-save-lives-516k</guid>
      <description>&lt;h2&gt;
  
  
  I thought errors were the enemy?
&lt;/h2&gt;

&lt;p&gt;Errors are often unwelcome and sometimes confusing elements that can throw a wrench into a seemingly logically sound program. Other times, error messages are succinct and easy to address. Though regardless of the type of error, we as programmers see them as a problem that is out of our control. What if that wasn't the case? What if we made our own errors?&lt;/p&gt;

&lt;h3&gt;
  
  
  Why custom errors?
&lt;/h3&gt;

&lt;p&gt;Custom errors in rails can be used by programmers to communicate to other programmers &lt;strong&gt;and&lt;/strong&gt; users that something has gone awry. A custom error can also be more specific and concise, making diagnosis and repair much easier than it would be otherwise. &lt;/p&gt;

&lt;h2&gt;
  
  
  Errors in ActiveRecord
&lt;/h2&gt;

&lt;p&gt;More often than not an error in ActiveRecord is destructive to the user experience and could point to a problem without showing the actual cause of the problem. For example, ActiveRecord may throw a RecordInvalid error not because something is wrong with the code, but because the user tried to submit a form with invalid values (think about password fields requiring characters or length.)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ms8zPTvM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsxil6wu9chve1wrptst.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ms8zPTvM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsxil6wu9chve1wrptst.png" alt="ActiveRecord error page" width="800" height="232"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the case of an ActiveRecord error, the output would be an error page that is confusing to a user without coding knowledge.&lt;/p&gt;

&lt;h3&gt;
  
  
  rescue_from
&lt;/h3&gt;

&lt;p&gt;What we can do to avoid this situation is to use rescue_from in a controller to quite literally rescue the program from an error that may be thrown by the ActiveRecord model. A rescue_from call may look something like this.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;rescue_from ActiveRecord::RecordInvalid, with: :record_invalid&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Every method call that may result in a RecordInvalid error will now be caught and then deferred to a method (:record_invalid) that we have defined elsewhere in the controller. Since this method won't be accessed outside of the class, we can make it private.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private

def record_invalid(invalid)
   render json: { errors: invalid.record.errors.full_messages }, status: :unprocessable_entity
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this bit of code, instead of a confusing page view, we now get a json response containing an array of error messages and a 422 status code (unprocessable entity) from the server. Since this specific error is caused by validations, through the magic of ActiveRecord, we get an array of messages that tell us which validations failed. We could also return our own messages by replacing the code within the brackets.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
def not_found
   render json: { errors: ["This thing was not found in that place"] }, status: :not_found
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We've changed a couple of things between the last example and this one but the idea stays the same; instead of an error page, we get an error status code and an array of messages. However, this time, the error message is something that we can set ourselves. For example, if we have a program that works off of a database of apples in an apple tree and someone tries to search for an avocado, we can return this error message ["This [AVOCADO] was not found in the [APPLE TREE]."] and/or any other relevant error messages. &lt;/p&gt;

&lt;h3&gt;
  
  
  How does this help the user?
&lt;/h3&gt;

&lt;p&gt;After the view receives the json response, it can then be used to communicate to the user that something has gone wrong. Instead of pulling the user out of the app to show them an error screen, since we have an array of error messages, we can just streamline these messages and display them in a way that the user can understand.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Fb5bFp3N--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgk9rxianpjm78lg04qw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Fb5bFp3N--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgk9rxianpjm78lg04qw.png" alt="Displaying errors to the user" width="660" height="358"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Much easier to understand than the error page that would display otherwise.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using error messages as a programmer
&lt;/h3&gt;

&lt;p&gt;In a development environment, code will often be run and rerun many times by multiple different programmers. So being able to communicate when and where something goes wrong is important. So just like the user, a programmer can use the error messages to either &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Test and isolate certain errors to make sure the user cannot do anything that should not be allowed.&lt;/li&gt;
&lt;li&gt;Test the application and receive accurate feedback on what needs to be fixed.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Usage outside of ActiveRecord
&lt;/h2&gt;

&lt;p&gt;We've been talking about rails this entire time but how can we practice using custom errors outside of Ruby and ActiveRecord? Most coding languages also have custom error implementation. It's very common for languages to have a way to 'throw' and 'catch' errors because that's how errors are usually dealt with internally. That's why an understanding bugs and debugging is a supremely important skill for developers. Using this skill to create meaningful custom errors only further adds to an app.&lt;/p&gt;

&lt;h3&gt;
  
  
  Building habits
&lt;/h3&gt;

&lt;p&gt;So how can you or I start coding with custom errors in mind? Without inflating our code with multiple error throws that don't make much sense, how can we apply this mode of thinking? One good place to start is to visualize how the code will run as you're building it. Is there a component of code that has many moving parts? We should throw an error at important junctions of that component so the problem is easier to diagnose. What if we threw error messages in sections of the program that will frequently interface with other bits of code? Although understanding good practice may be difficult at first, constantly asking questions and testing ideas may help build key habits that could be used throughout an entire career.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>SQL Joins - Drawing a Picture</title>
      <dc:creator>hyunho98</dc:creator>
      <pubDate>Mon, 28 Aug 2023 23:12:36 +0000</pubDate>
      <link>https://dev.to/hyunho98/sql-joins-drawing-a-picture-36fg</link>
      <guid>https://dev.to/hyunho98/sql-joins-drawing-a-picture-36fg</guid>
      <description>&lt;h2&gt;
  
  
  What Is A Join
&lt;/h2&gt;

&lt;p&gt;In the context of SQL, a programming language designed for coders to process information in a database, a Join is a way to connect two or more different tables that share data. One way we can illustrate this is by using the example of artists in a museum; an artist (table 1), may have many art pieces (table 2). Once an artist creates a piece of art, their connection to that art is immutable. However, artists also have names and art styles amongst many other personal traits. If an artist creates a piece of art, does it also take on these attributes? No, the art piece has its own traits such as a name, description, and time of completion. So in the context of a SQL database, how do we make this connection?&lt;/p&gt;

&lt;h2&gt;
  
  
  ID Association
&lt;/h2&gt;

&lt;p&gt;The conventional way of doing this is to assign an ID number to each instance of an artist or art piece. This is easy to do within a database table because you can assign the row number as a database entry's ID number. But how would we use this to connect artists to their art? The key to doing this is establishing a "has many/belongs to" relationship between the two. Since the relationship between an artist and their art is immutable, we can say that an artist &lt;strong&gt;has many&lt;/strong&gt; art pieces while an art piece can only &lt;strong&gt;belong to&lt;/strong&gt; one artist. Knowing this, we can add a column to the art pieces table that correlates to the ID number of the artist that created it. Now that we've established the visual connection, all we need to do is join the tables using code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Inner Joins
&lt;/h2&gt;

&lt;p&gt;The most common kind of Join in SQL is called an Inner Join. An inner join connects two tables and returns data that is shared between the two. Currently, in our artist/art example, the only connection we have between the two tables is the artist ID association. When using an inner join though, this information is all we need. Let's say that we have a list of every single art piece on display at a museum. However, this list is totally unorganized and we need to find all the art that is associated with a specific artist. In this table full of every different art piece we can execute this bit of code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT art_pieces.id, artists.name
FROM art_pieces
INNER JOIN artists ON art_pieces.artist_id = artist.id
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What does this do for us? This bit of code finds every single instance in the art_pieces table where the artist_id column of the art_pieces table matches the id column of the artists table. From there it gives us the id of the art piece as well as the name of the associated artist for every matching example. Now that we know where in the table our art pieces are located, we can now pass this information along to someone (or something) else that will sort this out for us.&lt;/p&gt;

&lt;h2&gt;
  
  
  Outer Joins
&lt;/h2&gt;

&lt;p&gt;The other kind of common join is called an Outer Join. While there are a few different kinds of outer joins, the most used amongst them are the &lt;strong&gt;Left Outer Join&lt;/strong&gt; and &lt;strong&gt;Right Outer Join&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Left Join
&lt;/h3&gt;

&lt;p&gt;The left join, like the inner join, pulls information that two tables share. However, it can also retrieves information from one table that is unrelated to the second. Using our museum example, we can set up a third table in our database called &lt;strong&gt;section&lt;/strong&gt;. We can set up a section with attributes like name and sponsor. Since a section can also have many artists, let's add a section_id column to artists so we can make the connection. What we can do with this information is set up a left join that might look something like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT sections.name, section.sponsor, artists.name
FROM sections
LEFT JOIN sections ON sections.id = artists.section_id
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This gives us all of the queried information in the left table, sections. Meaning that even if a section doesn't have a sponsor, it will still include that table entry in the result as NULL. This could be used to get a complete set of data regarding a museum's sections while only getting the associated data from the artists table.&lt;/p&gt;

&lt;h3&gt;
  
  
  Right Join
&lt;/h3&gt;

&lt;p&gt;The last of the commonly used joins, the right join, functions in a similar way to the left join. The left and right joins function in a similar way so they also look the same in practice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT sections.name, sections.sponsor, artists.name, artists.style
FROM sections
RIGHT JOIN sections ON sections.id = artists.id
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This join, unlike the left join, extracts information from the right table, artists, that may not have matches in sections. Meaning that any entry where sections does not have a sponsor will now not be included in the resulting join table while any entry in artists that does not have a style will now be featured as NULL in the new table.&lt;/p&gt;

&lt;h2&gt;
  
  
  Other Joins
&lt;/h2&gt;

&lt;p&gt;There are many other kinds of joins that are utilized by SQL coders such as the full outer join, self join, and cross join. However, these are more niche and require a little more understanding of SQL and its use cases.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>useState() and Props. When, Where, Why?</title>
      <dc:creator>hyunho98</dc:creator>
      <pubDate>Thu, 13 Apr 2023 07:25:27 +0000</pubDate>
      <link>https://dev.to/hyunho98/usestate-and-props-when-where-why-1ea0</link>
      <guid>https://dev.to/hyunho98/usestate-and-props-when-where-why-1ea0</guid>
      <description>&lt;h1&gt;
  
  
  Before State
&lt;/h1&gt;

&lt;p&gt;It's important that a programmer learns to utilize props before picking up State. This is because understanding props and information flow is imperative to building a well organized, structured program. Most of the organization of a program is done through the use of different components. Utilizing components in your program has two main benefits, &lt;strong&gt;flexibility&lt;/strong&gt; and &lt;strong&gt;reusability&lt;/strong&gt;. When you separate your code into components, you make your program more &lt;strong&gt;flexible&lt;/strong&gt; as a whole because individual components can be used and &lt;strong&gt;reused&lt;/strong&gt; in different places.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Component1() {
  return (
    &amp;lt;form&amp;gt;
      &amp;lt;input type="text" placeholder="First Name"/&amp;gt;
      &amp;lt;input type="text" placeholder="Last Name"/&amp;gt;
      &amp;lt;button&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}

default export Component1;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Take, for example, a simple First and Last name form. This component can be used in multiple locations for different purposes (What if you need the first and last name of the user? Maybe there's another page where you need the name of the user's family?) without having to repeat the code in those different locations. Components make fixing or adjusting code easier as well. Fixing or adjusting/adding to the component is much easier than scanning through every instance of a form to make the same change multiple times. But what happens when you submit that form? Where would the information go?&lt;/p&gt;

&lt;h2&gt;
  
  
  Introducing Props
&lt;/h2&gt;

&lt;p&gt;Props are used to send information between components. Because components in react consist of functions that return JSX, information flows through these components in the form of arguments to those functions in the form of props.&lt;br&gt;
&lt;code&gt;function Component1(props) {&lt;/code&gt;&lt;br&gt;
  Let's say in our form component we want to clarify what we want the user to put into the first and last name form. We can pass a string through the props argument. This happens when we import and call Component1 in a separate parent component.&lt;br&gt;
&lt;code&gt;&amp;lt;Component1 message="Enter your name" /&amp;gt;&lt;/code&gt;&lt;br&gt;
We can then access this message string in our form (Component1)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Component1(props) {
  const formMessage = props.message;
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;But what if we want to submit the form and send that information and send it back to the parent component?&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Using Callback Functions in Props
&lt;/h2&gt;

&lt;p&gt;If we wanted to send information back up the file tree, we would have to use a callback function. To make use of the callback function, we would have to build one first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
function formCallback(formData) {
  console.log(formData)
}
...
&amp;lt;Component1 message="Enter your name" formCallback={formCallback} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From here we would use the callback in our form component&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Component1(props) {
  const formMessage=props.message

  function submitHandler(e) {
    e.preventDefault()
    props.formCallback(e)
  }

  return (
    &amp;lt;form onSubmit={submitHandler}&amp;gt;
      &amp;lt;h2&amp;gt;{formMessage}&amp;lt;/h2&amp;gt;
      &amp;lt;input type="text" placeholder="First Name"/&amp;gt;
      &amp;lt;input type="text" placeholder="Last Name"/&amp;gt;
      &amp;lt;button&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whenever the user clicks on the submit button, the form information would then be sent to the parent component's callback function. From there the information can be used and operated on from the parent component.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But what if we wanted to operate on variables within the child component?&lt;/strong&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Enter the useState() Hook
&lt;/h1&gt;

&lt;p&gt;State is mainly used in react to retain information between renders. A benefit of this is the ability to use this persisting information in different components. To use useState(), the programmer must import the hook into their code.&lt;br&gt;
&lt;code&gt;import React, { useState } from "react"&lt;/code&gt;&lt;br&gt;
  From there, a state object can be created in the code. State should be used where the information is relevant but for our purposes, let's say that the form component is a child of two parent components which are also child components of our App component. We want both of App's child components to be able to access the state object, therefore, we'll create it in the App file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  const [message, setMessage] = useState("")

  return (
    &amp;lt;parentComponent1 message={message} setMessage={setMessage} /&amp;gt;
    &amp;lt;parentComponent2 message={message} setMessage={setMessage} /&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that when using the useState() hook, we declare two variables in an array. In simple terms, the first variable (message) is used as a getter, while the second variable (setMessage) is used as a setter.&lt;/p&gt;

&lt;p&gt;From here we can access the state variable and set the state variable in both parent components. We can use the setter variable in either to set the message of the variable to&lt;br&gt;
&lt;code&gt;setMessage("Enter your name")&lt;/code&gt;&lt;br&gt;
or&lt;br&gt;
&lt;code&gt;setMessage("Enter your mother's name")&lt;/code&gt;&lt;br&gt;
and then pass the getter variable to our form through either parent component&lt;br&gt;
&lt;code&gt;&amp;lt;Component1 message={message} formCallback={formCallback} /&amp;gt;&lt;/code&gt;&lt;br&gt;
from there we can access the message variable in our form&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Component1(props) {
  const formMessage=props.message

  function submitHandler(e) {
    e.preventDefault()
    props.formCallback(e)
  }

  return (
    &amp;lt;form onSubmit={submitHandler}&amp;gt;
      &amp;lt;h2&amp;gt;{formMessage}&amp;lt;/h2&amp;gt;
      &amp;lt;input type="text" placeholder="First Name"/&amp;gt;
      &amp;lt;input type="text" placeholder="Last Name"/&amp;gt;
      &amp;lt;button&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Depending on which parent component we use to call the form, the message being displayed at the top will differ. This adds further flexibility to our components because we can add custom elements to our component depending on the context in which we call it. Even if we were to render the form separately, when the setter function of the useState() hook is called, it will re-render the page while retaining the information that we store in the variable.&lt;/p&gt;

&lt;p&gt;Overall, it's easy to understand once a programmer gets used to thinking in terms of information flow. However, for the sake of cleanliness, efficiency, and keeping code DRY, programmers must practice storing information in only the relevant places.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Fetch Requests, Promises, and Asynchronous Code</title>
      <dc:creator>hyunho98</dc:creator>
      <pubDate>Sun, 15 Jan 2023 18:09:41 +0000</pubDate>
      <link>https://dev.to/hyunho98/fetch-requests-promises-and-asynchronous-code-4gj9</link>
      <guid>https://dev.to/hyunho98/fetch-requests-promises-and-asynchronous-code-4gj9</guid>
      <description>&lt;p&gt;What happens when a fetch request is made in JavaScript? Most of it happens under the hood so it's easy to skip over when learning how to code in JS. However, learning how exactly a fetch request interacts with the machine and server is imperative to writing efficient code.&lt;/p&gt;

&lt;p&gt;A quick summary of the order of operations when the machine runs a fetch request: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Interpreter encounters the &lt;code&gt;fetch()&lt;/code&gt; request&lt;/li&gt;
&lt;li&gt;The machine creates a separate executable stack for the request&lt;/li&gt;
&lt;li&gt;The machine continues running the program&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;meanwhile...&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;3a. The fetch request returns a &lt;strong&gt;promise&lt;/strong&gt;&lt;br&gt;
3b. The promise either returns resolved or rejected&lt;br&gt;
3c. If the promise is resolved, runs any subsequent &lt;code&gt;then()&lt;/code&gt; requests which also return promises which are then resolved/rejected&lt;/p&gt;
&lt;h2&gt;
  
  
  Why is the &lt;code&gt;fetch()&lt;/code&gt; request asynchronous code?
&lt;/h2&gt;

&lt;p&gt;Asynchronous code, put simply, is code that is set to run &lt;strong&gt;not&lt;/strong&gt; in sync with the rest of the code. Fetch requests automatically fall under asynchronous code due to the nature of a promise. Promises run for an indefinite length of time so to make sure the program doesn't freeze at a certain point, the lines of code are run &lt;strong&gt;while&lt;/strong&gt; the promise is waiting for resolution. And then whenever the promise is settled (when the promise is either resolved or rejected), the code goes back to the fetch request to either run (or not run) the rest of the fetch request or subsequent then statements.&lt;/p&gt;
&lt;h2&gt;
  
  
  What exactly causes the promise to run for an indefinite amount of time?
&lt;/h2&gt;

&lt;p&gt;To understand why the machine decides to allocate a separate place in memory to run the fetch request, it's important to know what exactly a promise does. A promise has three possible states:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Resolved&lt;/li&gt;
&lt;li&gt;Rejected&lt;/li&gt;
&lt;li&gt;Pending&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When a promise is either resolved or rejected, it is considered settled and the code within the fetch request is executed or skipped as a result. But even before that, the &lt;code&gt;fetch()&lt;/code&gt; line makes a request to an external server, during which, the promise is placed in a pending state. While in this pending state, the local machine must wait for a response from the server machine to continue executing the program. The server machine isn't expected to respond instantly and any responses from the server are subject to latency. This is why a fetch request's runtime is considered indefinite and is executed independently of the rest of the program.&lt;/p&gt;

&lt;p&gt;For example, here's an excerpt from my Flatiron phase 1 project, &lt;a href="https://github.com/hyunho98/coffee-bean-database"&gt;Coffee Bean Database&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('http://localhost:3000/coffee_beans')
  .then((response) =&amp;gt; response.json())
  .then((data) =&amp;gt; {
    console.log(2) //CONSOLE LOG 2
    data.forEach((bean) =&amp;gt; { 
      document.getElementById('tilecontainer')
      .append(createTile(bean))
        if (!locations.has(bean.location))
          createOption(bean.location)
    })
})
console.log(1) //CONSOLE LOG 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Of the two console log lines, which do you supposed runs first? Surprisingly enough, the code logs &lt;code&gt;1&lt;/code&gt; to the console before &lt;code&gt;2&lt;/code&gt; even though &lt;code&gt;console.log(2)&lt;/code&gt; occurs earlier in the code. Like in the example, this happens even when the server getting sent the request is running on a local machine. Depending on how long the server request takes, more lines of code may be run before the promise becomes settled. This must be kept in mind when creating or debugging asynchronous code as code that makes use of the data returned by a fetch request may encounter issues if the fetch request isn't settled by the time the compiler reaches it.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Flatiron Phase 1 - A Retrospective</title>
      <dc:creator>hyunho98</dc:creator>
      <pubDate>Sat, 07 Jan 2023 12:24:21 +0000</pubDate>
      <link>https://dev.to/hyunho98/flatiron-phase-1-a-retrospective-5do9</link>
      <guid>https://dev.to/hyunho98/flatiron-phase-1-a-retrospective-5do9</guid>
      <description>&lt;h2&gt;
  
  
  Phase 1 Project
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://github.com/learn-co-curriculum/phase-1-javascript-project-mode"&gt;Link&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Challenges&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Figuring out how to implement a star rating system and location filter was fun, though I believe that the answers I found were not the most efficient.&lt;/li&gt;
&lt;li&gt;Structuring my code in a way that made sense. I think that for the most part, I was successful in keeping my code DRY. However, I don't think I implemented functions in the most efficient way and in the process of trying to split up tasks into functions I believe I decreased overall readability.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Successes&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Implementing CSS and presenting the webpage in a way that makes sense to the user.&lt;/li&gt;
&lt;li&gt;Finding a solution for the star and filter feature that works in perpetuity. I believe that I coded the features in a way that does not rely on code from too many different locations in the program. Therefore, adding new features should not require too much restructuring.&lt;/li&gt;
&lt;li&gt;Code readability. For the most part, comments are short but get the general message across. Although I need more practice, reading through the code is not too difficult.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Failures&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Between the original mockup and the final product, I did not implement all the planned features. Some missing features include a search by keyword input field and filter by rating.&lt;/li&gt;
&lt;li&gt;I didn't keep adding comments in mind, so most comments are terse and don't contain specifics&lt;/li&gt;
&lt;li&gt;I did not manage my time well. Because I didn't manage my time well, some functions were added out of order or without structure in mind. To me, the code looks messy in some places due to this.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Improvements to be made&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Add more features. Not only will adding features flesh the program out towards what I had originally envisioned, It will also test the rigidity of the code that already exists.&lt;/li&gt;
&lt;li&gt;Keep &lt;strong&gt;Big O Notation&lt;/strong&gt; in mind. I'm interested in always improving efficiency and would like to be able to look at a snippet of code and find a way to make it run faster or take up less memory.&lt;/li&gt;
&lt;li&gt;Focus on improving readability. Human memory is limited and I won't be able to remember what every line of code's purpose. Even if just for my own sake, code needs to be readable.&lt;/li&gt;
&lt;li&gt;Improve on understanding context. For most of Phase 1, I went with the answer that came quickest to me instead of giving more thought to what the best answer might be. In retrospect, I probably used for loops much more often than I needed to.
e.g.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1,2,3]
const newArray = []
for (let i=0; i &amp;lt; array.length; i++)
   newArray.push(array[i] * 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;as opposed to&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1,2,3]
const newArray = array.map(x =&amp;gt; x * 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;To do list&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Get into the habit of putting more thought into the code I write. Find the best solution to a problem and make a mental note. Hopefully practice will make perfect and down the line I will be able to more naturally implement good practice.&lt;/li&gt;
&lt;li&gt;Be more mindful about adding comments. Add comments for every little thing and then shave them down later. Eventually, comments will become more intuitive and make more sense.&lt;/li&gt;
&lt;li&gt;Add code for features as they come to mind. Currently the biggest thing I missed is the search by keyword functionality. The pseudocode may look like this
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;grab values from text input box
grab values from the DOM
loop through DOM values
   test for matching values
hide all tiles that don't match
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Notes
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Before Phase 1, I took on extra responsibilities in other parts of my life. This definitely hindered my work-life balance and I struggled to manage my time as a result.
Remember: This is not your fault. Learn from this and know your limits and what works for you moving forwards.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Remember to communicate&lt;/strong&gt;. Even with all the hiccups, I have no excuse for not communicating that with the people that could help me most. Whether with confidants or my cohort lead, I should update the people in my life with relevant information so I'm not leaving them in the dark.&lt;/li&gt;
&lt;li&gt;Always work on having a regular schedule. I learn best when I build on top of habits. Even when you don't have any required work, set aside time. If you don't know what to do with that time, explore.&lt;/li&gt;
&lt;li&gt;Going into Phase 2 or any other future learning opportunities for that matter, &lt;strong&gt;take your time&lt;/strong&gt;. If a concept doesn't immediately stick, let it marinate and try to find uses for it in different contexts. This will give you a better understanding of how something works and when to best apply that information.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
  </channel>
</rss>
