<?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>Forem: victorhaynes</title>
    <description>The latest articles on Forem by victorhaynes (@victorhaynes).</description>
    <link>https://forem.com/victorhaynes</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%2F889265%2Fec458eb1-a923-4450-92f6-101e5fe4fb9f.png</url>
      <title>Forem: victorhaynes</title>
      <link>https://forem.com/victorhaynes</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/victorhaynes"/>
    <language>en</language>
    <item>
      <title>My Experience: Completing Flatiron School Software Engineering (Live) Bootcamp</title>
      <dc:creator>victorhaynes</dc:creator>
      <pubDate>Wed, 05 Oct 2022 17:06:24 +0000</pubDate>
      <link>https://forem.com/victorhaynes/my-experience-completing-flatiron-school-software-engineering-live-bootcamp-13j3</link>
      <guid>https://forem.com/victorhaynes/my-experience-completing-flatiron-school-software-engineering-live-bootcamp-13j3</guid>
      <description>&lt;h2&gt;
  
  
  The Stack (&amp;amp; core concepts)
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;JavaScript&lt;/strong&gt; (HTML + CSS, JSON Server, Request/Response Cycle)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;React&lt;/strong&gt; (React Router, Single Page Applications, Dynamic Re-rendering)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ruby&lt;/strong&gt; (OOP, ORMs, SQL, RESTful APIs)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ruby on Rails&lt;/strong&gt; (RESTful APIs /w framework)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The Cost:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Roughly $17,000&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The Timeline:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;5 Phases, each 3 weeks long&lt;/li&gt;
&lt;li&gt;JavaScript/HTML/CSS -&amp;gt; React as a frontend framework -&amp;gt; Ruby/OOP/SQL essentials -&amp;gt; Rails as a backend framework&lt;/li&gt;
&lt;li&gt;Phases 1 - 4 you work on and present group projects&lt;/li&gt;
&lt;li&gt;Phase 5 a 3 week long solo project&lt;/li&gt;
&lt;li&gt;15 weeks total duration + prework&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Phase Structure:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Roughly 1 week of learning a new concept (i.e. React)&lt;/li&gt;
&lt;li&gt;Roughly 1 week of preparing for a code challenge (i.e. React exam)&lt;/li&gt;
&lt;li&gt;Roughly 1 week of applying concepts to your phase project&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Pros:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Challenging. This is not something you can easily skim through. If you want something more lax that you can do at your own pace &amp;amp; learn at more of a dilettante-ish rate this is not that.&lt;/li&gt;
&lt;li&gt;Applicable content&lt;/li&gt;
&lt;li&gt;Namebrand bootcamp, higher quality than most&lt;/li&gt;
&lt;li&gt;Full stack program&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Neutral:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A pro or a con but you are 100% responsible for your own strength leaving the bootcamp. The staff is here to help but ultimately it's on you what you get out of this.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Cons:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A little bit of a sink or swim environment. If you set your mind to this you can do it. However it will require a lot of effort and self-reassuring along the way and there is no 2 ways about it. Especially if you are entirely new to technology.&lt;/li&gt;
&lt;li&gt;Expensive&lt;/li&gt;
&lt;li&gt;Rails is not as popular as it once was&lt;/li&gt;
&lt;li&gt;There is some self-guided material provided but CSS content is totally lacking&lt;/li&gt;
&lt;li&gt;Data structures &amp;amp; Algorithms (DSA) is treated as an after thought. There is self-guided material but realistically, very little time to do it if you want to complete all the core material with comprehension.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Recommendation?:
&lt;/h2&gt;

&lt;p&gt;Yes. If you can commit to the fulltime (online or in person does not matter) program.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Outcome:
&lt;/h2&gt;

&lt;p&gt;Pending, stay tuned for more.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>rails</category>
      <category>ruby</category>
    </item>
    <item>
      <title>Ruby on Rails: Serialization Made Easy</title>
      <dc:creator>victorhaynes</dc:creator>
      <pubDate>Sun, 11 Sep 2022 03:00:28 +0000</pubDate>
      <link>https://forem.com/victorhaynes/ruby-on-rails-serialization-made-easy-4kep</link>
      <guid>https://forem.com/victorhaynes/ruby-on-rails-serialization-made-easy-4kep</guid>
      <description>&lt;p&gt;&lt;em&gt;&lt;strong&gt;If you do not want an overview on how to setup a Rails API skip straight to part 2.&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Serialization&lt;/code&gt; in web development can simply be understood as the process of customizing the response our server sends (i.e. a Rails API) after receiving a request from a client (i.e. Goolge Chrome, Firefox, Safari etc.).&lt;/p&gt;

&lt;p&gt;Rails uses a gem/library called &lt;code&gt;'active_model_serializers'&lt;/code&gt; to give you easy, powerful response customization.&lt;/p&gt;

&lt;p&gt;For this explanation we will assume that we have a relational database based on SQL setup in our backend and have used some sort of ORM (Object Relationship Mapper) to turn OOP &lt;code&gt;objects&lt;/code&gt; into &lt;code&gt;models&lt;/code&gt;. Our &lt;code&gt;models&lt;/code&gt; each map to a table in our database and each instance of our &lt;code&gt;model&lt;/code&gt; is a record in our table.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Part 1: Setting up an API&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Skip if you are already comfortable quickly spinning up a Rails API. If you want a walk through we will be creating two resources. &lt;code&gt;Wallets&lt;/code&gt; (class &lt;code&gt;Wallet&lt;/code&gt;, table &lt;code&gt;wallets&lt;/code&gt;) and &lt;code&gt;Bills&lt;/code&gt; (class &lt;code&gt;Bill&lt;/code&gt;, table &lt;code&gt;bills&lt;/code&gt;)&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;Wallet&lt;/code&gt; has many &lt;code&gt;Bills&lt;/code&gt; and a &lt;code&gt;Bill&lt;/code&gt; belongs to a &lt;code&gt;Wallet&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;1) Create a new Rails app. I named mine &lt;code&gt;lets-learn-serializers&lt;/code&gt; used the &lt;code&gt;--api --minimal&lt;/code&gt; flags to keep the app light and extraneous features out.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ rails new lets-learn-serializers --api --minimal
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2) In &lt;code&gt;root/Gemfile&lt;/code&gt; add gem:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;gem "active_model_serializers", "~&amp;gt; 0.10.12"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3) &lt;code&gt;bundle install&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ bundle install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;4) Use a Rails &lt;code&gt;generator&lt;/code&gt; of your choice. The &lt;code&gt;scaffold&lt;/code&gt; generator creates many files for you following good coding practices and REST conventions. The &lt;code&gt;resource&lt;/code&gt; generator does a lot of heavy lifting for you but less pre-written code than scaffold. &lt;code&gt;--no-test-framework&lt;/code&gt; eliminates test files that Rails will generate for you. We do not need this now&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ rails g scaffold wallet owner brand --no-test-framework
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ rails g scaffold bill value:integer wallet:belongs_to --no-test-framework
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;5) Add the &lt;code&gt;has_many&lt;/code&gt; side of the relationship manually to the &lt;code&gt;Wallet&lt;/code&gt; model&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/wallet.rb

class Wallet &amp;lt; ApplicationRecord
    has_many :bills
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;6) Create your instances of &lt;code&gt;Wallet&lt;/code&gt;s and &lt;code&gt;Bill&lt;/code&gt;s (i.e. create Mock Data) in your &lt;code&gt;seeds.rb&lt;/code&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;example_wallets = [{owner: "Victor", brand: "Gucci"}, {owner: "Kells",brand: "Larry Leather"}, {owner: "Bart", brand: "Vintage Co."}]

example_bills = [{value: 20,wallet_id: 1},{value: 5, wallet_id: 1},{value: 1, wallet_id: 1},{value: 100,wallet_id: 2},{value: 100,wallet_id: 2},{value: 50,wallet_id: 3},{value: 20,wallet_id: 3}]

Wallet.create(example_wallets)
Bill.create(example_bills)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;7) Migrate and seed your database&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rails db:migrate db:seed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;8) If all goes well you should be left with 2 tables:&lt;br&gt;
&lt;code&gt;wallets&lt;/code&gt;:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbvscb0rv5yvble0muz75.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbvscb0rv5yvble0muz75.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;bills&lt;/code&gt;:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpoxmv7i2vafq6nw2fb7c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpoxmv7i2vafq6nw2fb7c.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;9) Check out your wallet and bills controllers, they should look something like this:&lt;br&gt;
&lt;code&gt;/app/controllers/wallets_controller.rb&lt;/code&gt;:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnjnyw3u9j8zn7xzuen0w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnjnyw3u9j8zn7xzuen0w.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we are ready to receive requests for CRUD actions on our &lt;code&gt;/wallets&lt;/code&gt; and &lt;code&gt;/bills&lt;/code&gt; resources. We can send information about our wallets and bills to a client.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Part 2: Serializing our Response&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Brief serializer explanation:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When we use the &lt;code&gt;render json:&lt;/code&gt; method in a model controller Rails defaults to sending everything about a given model to the client.&lt;/p&gt;

&lt;p&gt;A GET request to &lt;code&gt;/wallets&lt;/code&gt; will send back all of our &lt;code&gt;Wallet&lt;/code&gt; objects and each object will have the attributes: "owner", "brand", "created_at", "updated_at". Similarly, a GET request to &lt;code&gt;/bills&lt;/code&gt; will send back all of our &lt;code&gt;Bill&lt;/code&gt;s and their: "value", "wallet_id", "created_at", and "updated_at attributes". This is what you will get. No more and no less.&lt;/p&gt;

&lt;p&gt;If we want to change this default behavior (i.e. perform some sort of server-side calculation before sending a response back or excluding some information or literally anything other than "send everything back the way it is") the cleanest way to do so is to use a &lt;code&gt;Serializer&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Rails, usually for better, is an extremely opinionated framework. If you've gotten this far you've probably figured out that the way we name the building blocks of our MVC architecture in Rails matters, a lot. Rails does try to make it easy on us though as long as we know and follow the rules. &lt;strong&gt;By default, Rails will implcitly look for a serializer who's name matches the name of a model before sending back a response.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Put simply, before our &lt;code&gt;WalletsController&lt;/code&gt; sends anything anywhere it will look to see if a &lt;code&gt;WalletSerializer&lt;/code&gt; exists. If it does, it will use it. You can also specify what serializer you want to use should you have a need to but custom serializers are for another day.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Putting this in practice:&lt;/strong&gt;&lt;br&gt;
Let's take a look at our &lt;code&gt;Wallet&lt;/code&gt;s serializer now. The &lt;code&gt;$ rails g scaffold &amp;lt;model_name_here&amp;gt;&lt;/code&gt; command created this serializer for us. If you do not want all of the code scaffold gives you you can create a standalone serializer with &lt;code&gt;$ rails g serializer &amp;lt;singular_lowercase_model_name&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Depending on how you created your serializer your attributes will default to either &lt;code&gt;:id&lt;/code&gt; or all of the attributes excluding &lt;code&gt;:created_at&lt;/code&gt; and &lt;code&gt;:updated_at&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Using the &lt;code&gt;attributes&lt;/code&gt; keyword inside a model's serializer we can specify what we want to include in our JSON response to the client&lt;br&gt;
&lt;/p&gt;

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

class WalletSerializer &amp;lt; ActiveModel::Serializer
    attributes :id, :owner, :brand
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As is, a GET request to &lt;code&gt;/wallets&lt;/code&gt; returns this JSON response:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkeyi3hftnuqfpuc3d6wo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkeyi3hftnuqfpuc3d6wo.png" alt="Image description"&gt;&lt;/a&gt;And this makes total sense considering how our serializer for &lt;code&gt;Wallet&lt;/code&gt;s is setup. We got "id", "owner", and "brand" back. But hmmm, our timestamp columns from our &lt;code&gt;wallets&lt;/code&gt; table are being excluded. Let's add them back in.&lt;br&gt;
&lt;/p&gt;

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

class WalletSerializer &amp;lt; ActiveModel::Serializer
    attributes :id, :owner, :brand, :created_at, :updated_at
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our response now looks like this. For the rest of the blog I will keep the timestamps out for clarity:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnopqn6xdw81k4vw9vfg9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnopqn6xdw81k4vw9vfg9.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advanced uses:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In my view, there are two core tasks that &lt;code&gt;serializers&lt;/code&gt; help achieve other than just excluding/including information.&lt;/p&gt;

&lt;p&gt;1) Making use of the  &lt;strong&gt;associations&lt;/strong&gt; between models&lt;/p&gt;

&lt;p&gt;With very little effort, because we have the &lt;code&gt;Wallet&lt;/code&gt; -  &lt;code&gt;has_many :bills&lt;/code&gt; and &lt;code&gt;Bill&lt;/code&gt; - &lt;code&gt;belongs_to :wallet&lt;/code&gt; associations setup in our model we can include the association in our serializer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class WalletSerializer &amp;lt; ActiveModel::Serializer
  attributes :id, :owner, :brand

  has_many :bills
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And thanks to Ruby magic:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdi4icm63j9ebse7hu45o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdi4icm63j9ebse7hu45o.png" alt="Image description"&gt;&lt;/a&gt;We can now see that the wallet with id 1 or Victor's wallet has a $20, $5, and $1 bill. Kells has two $100 bills and etc.&lt;/p&gt;

&lt;p&gt;2) Including new, custom, or calculation-based information that is not in our database but needs to be sent to our front end.&lt;/p&gt;

&lt;p&gt;What if instead of knowing what kind of bill was inside each wallet we just wanted to know the total amount of money in each wallet? We can easily do that using some vanilla Ruby, ActiveRecord methods, and the functionality our serializer gives us. Let's write a &lt;code&gt;cash_total&lt;/code&gt; method to calculate this server-side and include the result in our JSON response&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class WalletSerializer &amp;lt; ActiveModel::Serializer
  attributes :id, :owner, :brand, :cash_total

  has_many :bills

  def cash_total
    self.object.bills.pluck(:value).sum
  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And just like that, you can now see that Victor has $26 in his Gucci wallet and Kells has $200 cash in his Larry Leather wallet.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5e7gq324dj5b9gty9u3a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5e7gq324dj5b9gty9u3a.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And that is enough information to start serializing your responses in reasonable ways. For continued learning experiment with serializing responses for the &lt;code&gt;Bill&lt;/code&gt; model/requests to &lt;code&gt;/bills&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I also recommend checking our the Ruby docs for custom serializers now that you have a strong foundation.&lt;/p&gt;

&lt;p&gt;Happy Rubying.&lt;/p&gt;

</description>
      <category>rails</category>
      <category>ruby</category>
      <category>api</category>
      <category>database</category>
    </item>
    <item>
      <title>ActiveRecord (a Ruby gem): Common Methods</title>
      <dc:creator>victorhaynes</dc:creator>
      <pubDate>Sat, 20 Aug 2022 20:35:44 +0000</pubDate>
      <link>https://forem.com/victorhaynes/activerecord-a-ruby-gem-common-methods-j96</link>
      <guid>https://forem.com/victorhaynes/activerecord-a-ruby-gem-common-methods-j96</guid>
      <description>&lt;p&gt;ActiveRecord is popular Ruby gem (library) that acts as an Object-Relational-Mapper (&lt;a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping"&gt;ORM&lt;/a&gt;) for Ruby.&lt;/p&gt;

&lt;p&gt;ActiveRecord allows us to combine the object-oriented nature of Ruby with the functionality of relational databases. Using ActiveRecord we can easily define Ruby Classes and map those Classes to columns in a database. We can then instantiate--i.e. create--new instances of those Ruby Classes and map those instances to records (rows) in a database column. We can then finally interact with our newly constructed database with methods from the ActiveRecord gem inside of a Ruby/.rb file.&lt;/p&gt;

&lt;p&gt;Before continuing please note that ActiveRecord uses strict naming conventions. This is what allows its default configuration to handle a lot of work for us.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;capitol, singular &lt;code&gt;Class&lt;/code&gt; name for your model (&lt;code&gt;Food&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;lowercase, plural table names (&lt;code&gt;foods&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Suppose we have this table of &lt;code&gt;foods&lt;/code&gt; (from a &lt;code&gt;Food&lt;/code&gt; Ruby &lt;code&gt;class&lt;/code&gt; &lt;code&gt;model&lt;/code&gt; that inherits from &lt;code&gt;ActiveRecord::Base&lt;/code&gt; if you are keeping track at home) :&lt;/p&gt;

&lt;h1&gt;
  
  
  Table: foods
&lt;/h1&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;id&lt;/th&gt;
&lt;th&gt;name&lt;/th&gt;
&lt;th&gt;tastiness&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;hotdog&lt;/td&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;burger&lt;/td&gt;
&lt;td&gt;7&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;ramen&lt;/td&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;rice&lt;/td&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;cheese&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;We could begin to access or manipulate this table using the &lt;code&gt;Food&lt;/code&gt; class in a rake console session for example or in the model's .rb file. Here are some common methods &amp;amp; manipulations:&lt;/p&gt;

&lt;h2&gt;
  
  
  get first record
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.first&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;=&amp;gt; &amp;lt;Object Instance corresponding to id:1 name: "hotdog" tastiness: 8&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;returns the first record/&lt;code&gt;Object&lt;/code&gt; instance in a column&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  get record by id
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.find(3)&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;=&amp;gt; &amp;lt;Object Instance corresponding to id:3 name: "ramen" tastiness: 9&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;returns the &lt;strong&gt;first&lt;/strong&gt; record/&lt;code&gt;Object&lt;/code&gt; instance with the &lt;code&gt;id&lt;/code&gt; passed as an argument&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  get record by attribute (first match only)
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.find_by(name: rice)&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;=&amp;gt; &amp;lt;Object Instance corresponding to id:4 name: "rice" tastiness: 10&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;returns the &lt;strong&gt;first&lt;/strong&gt; record/&lt;code&gt;Object&lt;/code&gt; instance with an attribute that matches the &lt;code&gt;.find_by()&lt;/code&gt; argument&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  get all records by criteria (all matches)
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.where(' tastiness &amp;lt; 8 ')&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;=&amp;gt; [&amp;lt;Object Instance corresponding to id:2 name: "burger" tastiness: 7&amp;gt;,
&amp;lt;Object Instance corresponding to id:5 name: "cheese" tastiness: 4&amp;gt;]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;returns all records/&lt;code&gt;Object&lt;/code&gt; instances with an attribute that matches what was passed as an argument&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.where&lt;/code&gt; returns an &lt;code&gt;ActiveRecord::Collection&lt;/code&gt; which is an &lt;code&gt;array&lt;/code&gt;-like data structure that can be indexed or iterated through using array methods. &lt;em&gt;Even if there is only 1 match &lt;code&gt;.where&lt;/code&gt; will always return the results in a collection.&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  get all values in a column
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.pluck(:name)&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;=&amp;gt; ["hotdog", "burger" , "ramen", "rice", "cheese"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Food.pluck(:tastiness)&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;=&amp;gt; [8, 7 , 9, 10, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;returns each value in a column as an element in an &lt;code&gt;array&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  create a new record/instance in a table (with persistence)
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.create(name: "eggs", tastiness: 5)&lt;/code&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;id&lt;/th&gt;
&lt;th&gt;name&lt;/th&gt;
&lt;th&gt;tastiness&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;hotdog&lt;/td&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;burger&lt;/td&gt;
&lt;td&gt;7&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;ramen&lt;/td&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;rice&lt;/td&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;cheese&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;6&lt;/td&gt;
&lt;td&gt;eggs&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;under the hood this is working similar to using &lt;code&gt;.new&lt;/code&gt; &amp;amp; &lt;code&gt;.save&lt;/code&gt; together. &lt;code&gt;.new&lt;/code&gt; will only create a new instance of a &lt;code&gt;class&lt;/code&gt; in Ruby memory. It will not persist until it is written to the database using &lt;code&gt;.save&lt;/code&gt;. &lt;code&gt;.create&lt;/code&gt; does both of these for you.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  count number of records in a column
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.count(:name)&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;=&amp;gt; 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;counts the number of records in a column&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  remove a record/instance in a table (with persistence)
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.find(2).destroy&lt;/code&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;id&lt;/th&gt;
&lt;th&gt;name&lt;/th&gt;
&lt;th&gt;tastiness&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;hotdog&lt;/td&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;ramen&lt;/td&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;rice&lt;/td&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;cheese&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;6&lt;/td&gt;
&lt;td&gt;eggs&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;.destroy&lt;/code&gt; should be used to destroy a single record/instance&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.destroy_all&lt;/code&gt; should be used to destroy multiple records such as every instance of a &lt;code&gt;class&lt;/code&gt; (i.e. &lt;code&gt;Food.destroy_all&lt;/code&gt;) or to destroy every member of an &lt;code&gt;ActiveRecord::Collection&lt;/code&gt; (i.e. after a &lt;code&gt;.where&lt;/code&gt; to do a targeted removal)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  update a record/instance in a table (with persistence)
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Food.find(6).update(name: "bread", tastiness: 9)&lt;/code&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;id&lt;/th&gt;
&lt;th&gt;name&lt;/th&gt;
&lt;th&gt;tastiness&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;hotdog&lt;/td&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;ramen&lt;/td&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;rice&lt;/td&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;cheese&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;6&lt;/td&gt;
&lt;td&gt;bread&lt;/td&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;you can update a single attribute such as only the name or only the tastiness or do both&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You are now familiar with basic &lt;code&gt;ActiveRecord&lt;/code&gt; ORM methods. If  you want to try experimenting with this data at home continue below:&lt;/p&gt;




&lt;h2&gt;
  
  
  Set this up at home:
&lt;/h2&gt;

&lt;p&gt;Provided you have an Ruby &amp;amp; ActiveRecord environment already configured and you are in that directory, you can try this yourself after creating (and migrating) this migration:&lt;/p&gt;

&lt;p&gt;Brief configuration guidance:&lt;br&gt;
&lt;code&gt;Gemfile&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;source "https://rubygems.org"

gem "activerecord", "~&amp;gt; 5.2"
gem "sinatra-activerecord"
gem "sqlite3"
gem "pry"
gem "require_all"
gem "rake"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Rakefile&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require_relative 'config/environment'
require 'sinatra/activerecord/rake'

desc 'starts a Pry console'
task :console do
  # Comment out the line below if you don't want to see the SQL logs in your terminal
  ActiveRecord::Base.logger = Logger.new(STDOUT)
  # Start a Pry session
  Pry.start
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;config/database.yml&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;config/environment.rb&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require 'bundler'
Bundler.require

require_all 'app'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, on to actually creating this database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# In a terminal window run:
$ bundle install
$ bundle exec rake db:create_migration NAME=create_foods
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# inside of the db/migrate folder
# update your migration to have these attributes
# (the 5.2 should match whatever version of the activerecord gem
# you have installed in your gemfile)

class CreateFoods &amp;lt; ActiveRecord::Migration[5.2]
  def change
    create_table :foods do |t|
      t.string :name
      t.integer :tastiness
    end
  end
end

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;migrate your newly created migration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# In a terminal window run:

$ bundle exec rake db:migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;create this model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# create a /app folder inside the root of your directory and put a /models folder inside of it.
# create a .rb file with your model name inside of /models 
# singular and lowercase i.e. /app/models/food.rb

class Food &amp;lt; ActiveRecord::Base
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;populate/seed your database with data (create instances of the Food class that will exist inside of your &lt;code&gt;foods&lt;/code&gt; table&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# create a "seeds.rb" file inside of the /db directory

Food.create(name: "hotdog", tastiness: 8)
Food.create(name: "burger", tastiness: 7)
Food.create(name: "ramen", tastiness: 9)
Food.create(name: "rice", tastiness: 10)
Food.create(name: "cheese", tastiness: 4)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# In a terminal window run:

$ bundle exec rake db:seed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You have now:&lt;br&gt;
1) Defined your table structure&lt;br&gt;
2) Created your table&lt;br&gt;
3) Defined what class belongs your the table&lt;br&gt;
4) Filled your table with instances of your class&lt;/p&gt;

&lt;p&gt;You can new view your database using an IDE + an extension (such as Visual Studio Code /w the SQLite extension or using a standalone database viewer app).&lt;/p&gt;

&lt;p&gt;Feel free to try access and manipulate your table inside of a &lt;code&gt;rake console&lt;/code&gt; session in your terminal or from inside your model's class definition now.&lt;/p&gt;

&lt;p&gt;Happy rubying!&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>beginners</category>
      <category>sql</category>
      <category>database</category>
    </item>
    <item>
      <title>React.js: Event Listeners Made Easy</title>
      <dc:creator>victorhaynes</dc:creator>
      <pubDate>Sun, 31 Jul 2022 21:39:00 +0000</pubDate>
      <link>https://forem.com/victorhaynes/reactjs-event-listeners-made-easy-2h9c</link>
      <guid>https://forem.com/victorhaynes/reactjs-event-listeners-made-easy-2h9c</guid>
      <description>&lt;p&gt;If you are a beginner webdev contemplating how to use Event Listeners in React, first of all congratulations on getting your foundation in vanilla JavaScript. That baseline JavaScript understanding is going to come in handy. Second of all, you are in the right place.&lt;/p&gt;

&lt;p&gt;Event Listeners in React work, for as far as we are concerned, almost identically to how they work in vanilla JavaScript. There are just some syntactic differences and they get attached to HTML elements in our DOM a bit differently.&lt;/p&gt;

&lt;h2&gt;
  
  
  The "vanilla JavaScript" way of doings things:
&lt;/h2&gt;

&lt;p&gt;In vanilla JavaScript you may be familiar with this sort of process:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 1) Create a new button HTML element &amp;lt;button&amp;gt;&amp;lt;/button&amp;gt;
const newButton = document.createElement("button")

// 2) Assign some attributes to the button
newButton.innerText = "Click Me!"
newButton.setAttribute("class","example-button")

// 3) Assign an Event Listener to the button
newButton.addEventListener("click", () =&amp;gt; console.log("You clicked me!")

// 4) Append this new button to the body of our HTML document (or anywhere else we want the button) in the DOM
document.body.append(newButton)

// 5) Your button is now visible on your example HTML page in browser and when clicked 
// it will print "You clicked me" in your console
// FYI: your new HTML button looks like this:
// &amp;lt;button class="example-button"&amp;gt;Click Me!&amp;lt;/button&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We call this style of programming &lt;code&gt;imperative&lt;/code&gt; programming. This means we are being extremely literal and precise. We are specifying every little step and providing clear instructions on how to achieve them. This is not a very React way of doings things. React introduces the concept of &lt;code&gt;declarative&lt;/code&gt; programming where we can "declare" what we want to happen and React will handle making it happen.&lt;/p&gt;

&lt;p&gt;This same example in React would look like this (assuming you have a React app already initialized). Let's start with a pretty clean slate:&lt;/p&gt;

&lt;h2&gt;
  
  
  Intro: The React way of doings things
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// This file is called App.js
// Here is our baseline React application, right now it only has a
// single Component called "App" and "App" just consists of a &amp;lt;div&amp;gt; node

import React from "react";


function App() {
  return (
    &amp;lt;div className="App"&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;Notice how inside the return statement of &lt;code&gt;App&lt;/code&gt; it looks like we are writing HTML syntax. That is because we are essentially are with some minor differences (ex. &lt;code&gt;class&lt;/code&gt; is used in HTML where in React we use &lt;code&gt;className&lt;/code&gt;). &lt;code&gt;React Components&lt;/code&gt; render JSX. JSX is a JavaScript extension that allows us to use HTML-like syntax directly inside of a .js file. This is useful because now we can use vanilla JavaScript, HTML, and React-specific features all in the same single .js file. Lets try to build out our vanilla example in React.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example (pt. 1) - make a button node
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Here we added a button inside of our &amp;lt;div&amp;gt;&amp;lt;/div&amp;gt;

import React from "react";


function App() {
  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;button className="example-button"&amp;gt;Click Me!&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;Wait. What happened to &lt;code&gt;document.createElement("button")&lt;/code&gt; and &lt;code&gt;.setAttribute("class", "some-example-class")&lt;/code&gt;? In React we no longer need these methods. We can straight up type the HTML we want to render along with any &lt;code&gt;id&lt;/code&gt;s or &lt;code&gt;class&lt;/code&gt;es directly. We also do not need to &lt;code&gt;.append()&lt;/code&gt; anything to our DOM.&lt;/p&gt;

&lt;p&gt;If you care to know how exactly these &lt;code&gt;React Components&lt;/code&gt; and JSX are getting rendered, &lt;a href="https://create-react-app.dev/docs/getting-started/"&gt;the &lt;code&gt;index.js&lt;/code&gt; file that is auto generated upon initializing a React app is how.&lt;/a&gt; But there are a host of other concepts that make it all happen which are a topic for a different day.&lt;/p&gt;

&lt;p&gt;Let's just get an Event Listener working in React. Instead of using &lt;code&gt;.addEventListener()&lt;/code&gt; on an HTML node using vanilla JavaScript we can directly add an Event Listener to the JSX node inside the same, single file!&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Vanilla JavaScript&lt;/th&gt;
&lt;th&gt;React&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;.addEventListener("click", ...&lt;/td&gt;
&lt;td&gt;onClick=&lt;code&gt;{someFunction}&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;.addEventListener("submit", ...&lt;/td&gt;
&lt;td&gt;onSubmit=&lt;code&gt;{someFunction}&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;.addEventListener("hover", ...&lt;/td&gt;
&lt;td&gt;onHover=&lt;code&gt;{someFunction}&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;.addEventListener("change", ...&lt;/td&gt;
&lt;td&gt;onChange=&lt;code&gt;{someFunction}&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;etc.&lt;/td&gt;
&lt;td&gt;etc.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Just like how we straight-up-typed the div, the button, the button's innerText, and assigned a class all inside the JSX we can straight-up-type the event listener we want on the JSX also.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example (pt. 2) - add an onClick to our button &amp;amp; a function to handle the click event
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 1) We defined a function to handle the click event
// 2) We added an onClick event inside the &amp;lt;button&amp;gt; tag

import React from "react";


function App() {

  function handleClick(){
    console.log("You clicked me!")
  }

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;button className="example-button" onClick={handleClick}&amp;gt;
        Click Me!
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;React Event Listeners must be set equal to something. You want the event listener to be set equal to the function you want to run when the event happens. Specifically, you want to use a &lt;code&gt;function definition&lt;/code&gt; and not a &lt;code&gt;function invocation&lt;/code&gt;. When our button is clicked on the React application/webpage in our example, "You clicked me!" will be fired off in our console just like in our vanilla JavaScript example.&lt;/p&gt;

&lt;p&gt;If you wanted to refactor this a bit you could also the define the post-event-instructions directly inside the &lt;code&gt;onClick&lt;/code&gt; and this will achieve the same thing:&lt;/p&gt;

&lt;h2&gt;
  
  
  Example (pt. 2a) - refactor, define the handler function inline
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function App() {

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;button className="example-button" onClick={() =&amp;gt; console.log("You clicked me!")}&amp;gt;
        Click Me!
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;But back to our &lt;strong&gt;Example part 2&lt;/strong&gt;. There are a few other things going on here. Inside of the same App.js file we are able to 1) write vanilla javascript where we defined our function &lt;code&gt;handleClick&lt;/code&gt; and 2) make use of JSX inside of our &lt;code&gt;React Component&lt;/code&gt; (inside of &lt;code&gt;App&lt;/code&gt;'s return statement). Another thing to call out is our use of curly braces &lt;code&gt;{}&lt;/code&gt;. Inside the return statement of a &lt;code&gt;React Component&lt;/code&gt; the default expectation is everything you type will be JSX. If you need to &lt;code&gt;interpolate&lt;/code&gt; vanilla JavaScript inside the return statement of a &lt;code&gt;Component&lt;/code&gt; you must wrap the JavaScript inside curly braces &lt;code&gt;{like So}&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  And..... Done!
&lt;/h2&gt;

&lt;p&gt;Congratulations on getting this far in your journey towards web development. You are now equipped with the fundamentals on how to use &lt;code&gt;Event Listeners&lt;/code&gt; in React.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
    <item>
      <title>JavaScript: Event Listeners made easy</title>
      <dc:creator>victorhaynes</dc:creator>
      <pubDate>Wed, 13 Jul 2022 02:14:53 +0000</pubDate>
      <link>https://forem.com/victorhaynes/javascript-event-listeners-made-easy-663</link>
      <guid>https://forem.com/victorhaynes/javascript-event-listeners-made-easy-663</guid>
      <description>&lt;p&gt;Looking for a beginner-friendly example? Skip to the end.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why am I writing this?
&lt;/h2&gt;

&lt;p&gt;If you are not already an expert programmer, digesting a new concept is often daunting. There is no way around the fact that it takes time and effort for the next topic in your learning journey to sink in. This is further compounded by the fact there are many places to search for help and they are all wrapped in their own assumptions, intentions, and shorthands. It is often said that &lt;em&gt;Googling&lt;/em&gt; is an important skill to develop--and it absolutely is!&lt;/p&gt;

&lt;p&gt;Equally important however, is at this stage we must realize some sources are more helpful than others. If you have been programing for weeks or months, the Mozilla Developer Network (MDN) is not the best place to go to initially understand a foundational concept. A colleague of mine put it best. MDN is a great place to go when you want to have "beard-stroking, programming philosophizing time." It is a great place to get exhaustive, 100% technically correct answers but the target audience is not beginners. If you are new to event listeners &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener"&gt;this explanation may not help you&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you are a true beginner looking for help on an assignment or if want to see a basic example of a concept, you likely do not care about all of the optional parameters of a method or function. Nor do you particularly care about the technical constraints of this particular built-in JavaScript method versus a similar looking built-in method. So let me be clear about the intentions of my blog post. If you want to start making richer webpages &lt;em&gt;now&lt;/em&gt;...I give you: &lt;strong&gt;Event Listeners Made Easy.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's begin: what is an Event Listener?
&lt;/h2&gt;

&lt;p&gt;The cool thing about programming is that you can often think through tasks verbally and literally. It is important to remember that we humans are the smart ones and the computers are the dumb ones. The syntax to create an event listener is &lt;code&gt;.addEventListener()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is a &lt;code&gt;method&lt;/code&gt; built into &lt;code&gt;JavaScript&lt;/code&gt; by our programming predecessors, very kind of them. They were even kind enough to give &lt;code&gt;.addEventListener()&lt;/code&gt; a very &lt;em&gt;meaningful&lt;/em&gt; name and syntax. If we stop and think through this literally: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We are &lt;strong&gt;adding&lt;/strong&gt; an "Event Listener" to something.&lt;/li&gt;
&lt;li&gt;We are indicating that we are &lt;strong&gt;listening&lt;/strong&gt; or waiting for a certain &lt;strong&gt;event to happen to&lt;/strong&gt; our something.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Typically, we are adding this "Event Listener" onto a &lt;code&gt;HTML element&lt;/code&gt; inside the &lt;code&gt;document&lt;/code&gt; in the DOM. Let's talk through a basic example:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We target a specific &lt;code&gt;HTML element&lt;/code&gt; in the DOM&lt;/li&gt;
&lt;li&gt;We apply the &lt;code&gt;method&lt;/code&gt; &lt;code&gt;.addEventListener()&lt;/code&gt; to our &lt;code&gt;HTML element&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;We then want to pass 2 arguments into &lt;code&gt;.addEventListener()&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;The first argument is the type of event we are looking for (i.e. &lt;code&gt;"click"&lt;/code&gt; to listen for a mouse click, &lt;code&gt;"submit"&lt;/code&gt; to listen for a form submission etc.)&lt;/li&gt;
&lt;li&gt;The second argument is the &lt;code&gt;function&lt;/code&gt; or the work we want to kick off once our specified event happens to our &lt;code&gt;HTML Element&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In general, a basic &lt;code&gt;.addEventListener()&lt;/code&gt; setup has two parameters (yes there are additional optional parameters if you check MDN). A high level example looks something like this:&lt;br&gt;
&lt;code&gt;some HTML Element&lt;/code&gt; &lt;code&gt;.addEventListener&lt;/code&gt;(&lt;code&gt;"name of event"&lt;/code&gt; ,&lt;code&gt;some function&lt;/code&gt;)&lt;/p&gt;

&lt;p&gt;Example recognized events are: &lt;code&gt;"click"&lt;/code&gt;, &lt;code&gt;"keydown"&lt;/code&gt;, &lt;code&gt;"keyup"&lt;/code&gt;, &lt;code&gt;"keypress"&lt;/code&gt;, &lt;code&gt;"submit"&lt;/code&gt;, &lt;code&gt;"mouseover"&lt;/code&gt; etc. Again, we owe a debt to our programming predecessors. They already equipped &lt;code&gt;JavaScript&lt;/code&gt; with the ability to recognize when common mouse and keyboard actions occur.&lt;br&gt;
Let's look at a real example now.&lt;/p&gt;
&lt;h2&gt;
  
  
  Example code
&lt;/h2&gt;

&lt;p&gt;Suppose you have the following &lt;code&gt;HTML&lt;/code&gt; code in your DOM:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id ="info"&amp;gt;
     &amp;lt;button id="example-button"&amp;gt;Click Me!&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;--! This is merely a &amp;lt;button&amp;gt; HTML element that will --&amp;gt; 
&amp;lt;--! read "Click Me!" when rendered in a web browser --&amp;gt;
&amp;lt;--! and the button is nested inside a &amp;lt;div&amp;gt; element --&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This button is not very useful right now. Sure it appears on our webpage but it is missing &lt;em&gt;behavior&lt;/em&gt;. When you click this button it will not do anything. To add &lt;em&gt;behavior&lt;/em&gt; to an &lt;code&gt;HTML element&lt;/code&gt; we apply the &lt;code&gt;.addEventListener()&lt;/code&gt; &lt;code&gt;method&lt;/code&gt; to our &lt;code&gt;HTML element&lt;/code&gt; using &lt;code&gt;JavaScript&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's write some &lt;code&gt;JavaScript&lt;/code&gt; code to achieve this. For a quick review, we first need to target the &lt;code&gt;HTML element&lt;/code&gt; in our DOM that contains our button using &lt;code&gt;.querySelector()&lt;/code&gt; or &lt;code&gt;.getElementById()&lt;/code&gt;. I will use &lt;code&gt;.querySelector()&lt;/code&gt; just to demonstrate how specific you can be with your query. Yes we can use &lt;code&gt;.getElementById()&lt;/code&gt; with less code in this example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let buttonElement = document.querySelector("div#info button")

// This line of code targets our &amp;lt;button&amp;gt; HTML element
// that is nested inside that parent &amp;lt;div&amp;gt;
// and stores it in variable buttonElement.

buttonElement.addEventListener("click", () =&amp;gt; {
   console.log("You Clicked The Button!")
   console.log("If you see this, your Event Listener works!")
})

// Here, we added an Event Listener onto our HTML button
// and specified the "click" event as the 1st argument.
// As the 2nd argument we passed in an anonymous function
// using arrow syntax. The function we passed in this case
// has no name or parameters. They are not explicitly necessary
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have just done something very powerful. We took some &lt;strong&gt;static&lt;/strong&gt; HTML and made it &lt;strong&gt;dynamic&lt;/strong&gt;. Now when we click that "Click Me!" on our webpage i.e. when we click on this button:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id ="info"&amp;gt;
     &amp;lt;button id="example-button"&amp;gt;Click Me!&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we can specify to make some code to run. Inside the &lt;code&gt;.addEventListener()&lt;/code&gt; we wrote, we specified instructions that will run after our button is clicked. The &lt;code&gt;anonymous function&lt;/code&gt; passed inside as the 2nd argument will trigger and simply print to the &lt;code&gt;console&lt;/code&gt; "You Clicked The Button!" and "If you see this, your Event Listener works!" but that is already a beautiful start. We could make that &lt;code&gt;function&lt;/code&gt; much more robust. We could name and define a more complex &lt;code&gt;function&lt;/code&gt; in the &lt;code&gt;global scope&lt;/code&gt; and pass it into our &lt;code&gt;.addEventListener()&lt;/code&gt; as the second argument. We could have that more robust &lt;code&gt;function&lt;/code&gt; specify instructions to append some new information into our DOM once our webpage user clicks our button. We could even specify instructions to send data to a server and have that data persist in the server once our button is clicked even after we close our webpage. But for now, we have event listeners working and that is a victory.&lt;/p&gt;

&lt;p&gt;You now understand the syntax and the basic parameters of &lt;code&gt;.addEventListener()&lt;/code&gt; and can start to add &lt;code&gt;"click"&lt;/code&gt; events to your &lt;code&gt;HTML Elements&lt;/code&gt; in the DOM.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>dom</category>
    </item>
  </channel>
</rss>
