<?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: Martin Souza</title>
    <description>The latest articles on Forem by Martin Souza (@souzamartin).</description>
    <link>https://forem.com/souzamartin</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%2F963607%2Fd89eb046-98e9-4aa2-a2e9-20d599f0e558.jpeg</url>
      <title>Forem: Martin Souza</title>
      <link>https://forem.com/souzamartin</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/souzamartin"/>
    <language>en</language>
    <item>
      <title>Rescue Me: Techniques for Active Record Error Handling in Ruby on Rails</title>
      <dc:creator>Martin Souza</dc:creator>
      <pubDate>Thu, 05 Jan 2023 20:15:11 +0000</pubDate>
      <link>https://forem.com/souzamartin/rescue-me-techniques-for-active-record-error-handling-in-ruby-on-rails-4mo1</link>
      <guid>https://forem.com/souzamartin/rescue-me-techniques-for-active-record-error-handling-in-ruby-on-rails-4mo1</guid>
      <description>&lt;p&gt;Active Record provides many mighty tools to streamline the work of building a backend API, including for when things go wrong. In this post, we'll walk through three error-handling techniques, getting more sophisticated and powerful as we go.&lt;/p&gt;

&lt;p&gt;For the sake of simplicity, our examples will deal with failing to find a record in our database, which we'll illustrate in the context of a standard, RESTful &lt;code&gt;show&lt;/code&gt; controller action. However, these techniques are applicable to other types of errors as well.&lt;/p&gt;

&lt;h3&gt;
  
  
  Basic Error-Handling with Conditional Logic
&lt;/h3&gt;

&lt;p&gt;The simplest way to handle Active Record errors is just to use conditional logic in your controller actions to specify what your API should do if an error arises. We might write our &lt;code&gt;show&lt;/code&gt; action like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;show&lt;/span&gt;
  &lt;span class="n"&gt;dingus&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;Dingus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find_by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;id: &lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:id&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dingus?&lt;/span&gt;
    &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="n"&gt;dingus&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;status: :ok&lt;/span&gt;
  &lt;span class="k"&gt;else&lt;/span&gt;
    &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="ss"&gt;error: &lt;/span&gt;&lt;span class="s2"&gt;"Dingus not found"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="ss"&gt;status: :not_found&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's break down what's happening here. First, we initialize a variable to refer to the &lt;code&gt;Dingus&lt;/code&gt; record we want from the database, and we use &lt;code&gt;find_by&lt;/code&gt; to retrieve it with the &lt;code&gt;id&lt;/code&gt; provided by the params hash. (Read more about the params hash &lt;a href="https://dev.to/souzamartin/whose-params-are-they-anyway-using-the-params-hash-in-rails-12ke"&gt;here&lt;/a&gt;.) Then, the conditional statement &lt;code&gt;if dingus?&lt;/code&gt; checks whether that variable has a truthy or falsey value. This works because if the &lt;code&gt;find_by&lt;/code&gt; operation locates a record and assigns it to the variable, &lt;code&gt;dingus&lt;/code&gt; is truthy. If no record is found, the value of &lt;code&gt;dingus&lt;/code&gt; is &lt;code&gt;nil&lt;/code&gt;, which is falsey. Accordingly, if the condition is met, the API sends the data in its response, along with the successful &lt;code&gt;:ok&lt;/code&gt; status code. Otherwise, it sends an error message, which we've produced manually as a simple hash, along with the appropriate &lt;code&gt;:not_found&lt;/code&gt; status.&lt;/p&gt;

&lt;p&gt;Handling errors like this has certain advantages. For one thing, this approach is easy to understand, and all the code for it exists in one place. It gives you very specific control over how an individual controller action responds to a certain error, and for that reason this technique can sometimes be useful even if you're using other more sophisticated methods elsewhere—particularly if you're creating custom controller actions.&lt;/p&gt;

&lt;p&gt;However, for common errors, this technique is inefficient and clunky. You don't want to have to write separate &lt;code&gt;if&lt;/code&gt;/&lt;code&gt;else&lt;/code&gt; logic everywhere, and you definitely shouldn't compose your own error messages for every single case.&lt;/p&gt;

&lt;h3&gt;
  
  
  Basic Error-Handling with Rescue Blocks
&lt;/h3&gt;

&lt;p&gt;Fortunately, Active Record gives us more tools and a better way to do things. In our first example, we used a simple logical condition to check whether or not our &lt;code&gt;show&lt;/code&gt; action found a record, but we can take advantage of some built-in functionality instead.&lt;/p&gt;

&lt;p&gt;Certain Active Record methods return instances of special classes called &lt;strong&gt;exceptions&lt;/strong&gt; in the event of failure. For instance, the &lt;code&gt;find&lt;/code&gt; method takes an &lt;code&gt;id&lt;/code&gt; and returns a &lt;code&gt;RecordNotFound&lt;/code&gt; exception if there's no record with a matching &lt;code&gt;id&lt;/code&gt; attribute. It is less flexible than the &lt;code&gt;find_by&lt;/code&gt; method in our first example, which can search using whatever attribute we like, but returning an exception instead of just &lt;code&gt;nil&lt;/code&gt; when it doesn't find a matching record is a major advantage. For one thing, exceptions come with their own error messages, which we can access and send to the frontend rather than having to compose them ourselves. More importantly, they also enable us to use &lt;strong&gt;rescue blocks&lt;/strong&gt; to define how we want to handle errors.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;rescue&lt;/code&gt; keyword is kind of like special conditional logic that looks out for exceptions of the specified type. When the right kind of exception occurs, the code block runs, doing whatever we've written to deal with the error.&lt;/p&gt;

&lt;p&gt;Let's rewrite our &lt;code&gt;show&lt;/code&gt; action to use a rescue block:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;show&lt;/span&gt;
  &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="no"&gt;Dingus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:id&lt;/span&gt;&lt;span class="p"&gt;]),&lt;/span&gt; &lt;span class="ss"&gt;status: :ok&lt;/span&gt;
&lt;span class="k"&gt;rescue&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;RecordNotFound&lt;/span&gt;
  &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="ss"&gt;error: &lt;/span&gt;&lt;span class="s2"&gt;"Dingus not found"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="ss"&gt;status: :not_found&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we're using &lt;code&gt;find&lt;/code&gt; to retrieve the requested record, and simply sending it to the frontend without assigning it to a variable first (though you can certainly still do so, and might have reason to in certain cases). If no record exists with a matching &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;find&lt;/code&gt; returns an &lt;code&gt;ActiveRecord::RecordNotFound&lt;/code&gt; exception—and when that happens, our rescue block kicks in and runs the same code we used in the &lt;code&gt;else&lt;/code&gt; part of our first example.&lt;/p&gt;

&lt;p&gt;This is a step in the right direction, but we still have to write a rescue block for each controller action. Maybe that's fine if we want to deal with a certain kind of exception for a single action, but it's annoying if we want to handle the same kinds of errors in multiple places.&lt;/p&gt;

&lt;h3&gt;
  
  
  Intermediate Error-Handling with &lt;code&gt;rescue_from&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;Fortunately, we can entirely separate our error-handling from our controller actions. Just like &lt;code&gt;rescue&lt;/code&gt;, &lt;code&gt;rescue_from&lt;/code&gt; defines a response to a specific type of exception. However, rather than being attached to a particular action, a &lt;code&gt;rescue_from&lt;/code&gt; is independently defined, and applies any time the specified exception occurs, no matter what action it comes from.&lt;/p&gt;

&lt;p&gt;With a &lt;code&gt;rescue_from&lt;/code&gt;, our whole example controller now looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DingusesController&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ApplicationController&lt;/span&gt;
  &lt;span class="n"&gt;rescue_from&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;RecordNotFound&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;with: :render_not_found&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;show&lt;/span&gt;
    &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="no"&gt;Dingus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:id&lt;/span&gt;&lt;span class="p"&gt;]),&lt;/span&gt; &lt;span class="ss"&gt;status: :ok&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;

  &lt;span class="kp"&gt;private&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;render_not_found&lt;/span&gt;
    &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="ss"&gt;error: &lt;/span&gt;&lt;span class="s2"&gt;"Dingus not found"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="ss"&gt;status: :not_found&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the &lt;code&gt;show&lt;/code&gt; action doesn't need to include anything concerned with potential errors. We've refactored the error response into a separate method called &lt;code&gt;render_not_found&lt;/code&gt;, which our &lt;code&gt;rescue_from&lt;/code&gt; will use whenever a &lt;code&gt;RecordNotFound&lt;/code&gt; exception occurs.&lt;/p&gt;

&lt;p&gt;At this point, since our error-handling is separated from our controller actions, we can make it even more generally performant by relocating it to our top-level controller, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ApplicationController&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActionController&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;API&lt;/span&gt;
  &lt;span class="n"&gt;rescue_from&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;RecordNotFound&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;with: :render_not_found&lt;/span&gt;

  &lt;span class="kp"&gt;private&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;render_not_found&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;model&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Not found"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="ss"&gt;status: :not_found&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since &lt;code&gt;DingusesController&lt;/code&gt; inherits from &lt;code&gt;ApplicationController&lt;/code&gt;, it will use the &lt;code&gt;rescue_from&lt;/code&gt; defined there—as will all our other controllers. We've also adjusted the private &lt;code&gt;render_not_found&lt;/code&gt; method in order to generalize and reuse our error response whenever a &lt;code&gt;RecordNotFound&lt;/code&gt; exception occurs anywhere. Now it takes the exception instance as a parameter so we can call &lt;code&gt;exception.model&lt;/code&gt; to get whatever kind of resource wasn't found. In our example case, this would give us &lt;code&gt;{Dingus: "Not found"}&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  TLDR
&lt;/h3&gt;

&lt;p&gt;The best approach for handling most Active Record errors in to use &lt;code&gt;rescue_from&lt;/code&gt; in your top-level application controller. It's a bit more abstract, but it's the most effective and efficient way to cover common types of errors for multiple database resources. Once you understand how to use &lt;code&gt;rescue_from&lt;/code&gt;, there's probably little reason to ever use an individual rescue block.&lt;/p&gt;

&lt;p&gt;However, there may be still be times where good old &lt;code&gt;if&lt;/code&gt;/&lt;code&gt;else&lt;/code&gt; logic can provide a good one-off solution to deal with errors in special cases.&lt;/p&gt;

</description>
      <category>rails</category>
      <category>ruby</category>
      <category>api</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Whose Params Are They Anyway? Using the Params Hash in Rails</title>
      <dc:creator>Martin Souza</dc:creator>
      <pubDate>Tue, 13 Dec 2022 21:33:26 +0000</pubDate>
      <link>https://forem.com/souzamartin/whose-params-are-they-anyway-using-the-params-hash-in-rails-12ke</link>
      <guid>https://forem.com/souzamartin/whose-params-are-they-anyway-using-the-params-hash-in-rails-12ke</guid>
      <description>&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note:&lt;/strong&gt; This post discusses the params hash in the context of Ruby on Rails, but the essential details also apply if you're using Sinatra for your Ruby API.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In learning about writing server APIs and setting up backend routing over the last few weeks, one of the trickiest concepts to pin down was the params hash. In dynamic routing, this special little data structure somewhat mysteriously performs a dual role in accessing information from incoming requests. Like most things I've encountered in programming that behave differently in different contexts, I took note of the params hash as a potential source of confusion for new programmers like myself (or simply anyone new to Ruby APIs).&lt;/p&gt;

&lt;p&gt;To hopefully alleviate or avoid such confusion, let's look at what the params hash does and how to use it for handling different types of client requests.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Even Is This?
&lt;/h3&gt;

&lt;p&gt;First off, of course: what is the params hash? As the name tells us, it's a &lt;strong&gt;hash&lt;/strong&gt; (a collection data structure with key-value pairs) that contains certain &lt;strong&gt;parameters&lt;/strong&gt;. What exactly those parameters are and where they come from is what varies from case to case, and thus where confusion is likely to arise.&lt;/p&gt;

&lt;p&gt;Broadly speaking, the params hash contains information included with HTTP requests. Depending on the type of request, it may include &lt;strong&gt;dynamic path information&lt;/strong&gt; from the request URL, information from the &lt;strong&gt;request body&lt;/strong&gt;, or &lt;strong&gt;both&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using the Params Hash with Dynamic Routes
&lt;/h3&gt;

&lt;p&gt;We see the first and plainest of the params hash's two faces when we write dynamic backend routes like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="c1"&gt;# in config/routes.rb&lt;/span&gt;
&lt;span class="n"&gt;get&lt;/span&gt; &lt;span class="s1"&gt;'/dinguses/:id'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;to&lt;/span&gt; &lt;span class="s1"&gt;'dinguses#show'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is one of the basic RESTful routes most Rails APIs will have for typical CRUD operations. In this case, a request to this route should return a single record from our database for the dingus resource matching a specified &lt;code&gt;id&lt;/code&gt;. So if our API receives a &lt;code&gt;GET&lt;/code&gt; request to &lt;code&gt;/dinguses/3&lt;/code&gt;, it should return the dingus from our database with an &lt;code&gt;id&lt;/code&gt; of 3.&lt;/p&gt;

&lt;p&gt;The params hash is how our API accesses the actual value provided for that &lt;code&gt;id&lt;/code&gt; in a given request. Specifically, we can refer to the params hash in the appropriate controller to get this value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DingusesController&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ApplicationController&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;show&lt;/span&gt;
    &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="no"&gt;Dingus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:id&lt;/span&gt;&lt;span class="p"&gt;]),&lt;/span&gt; &lt;span class="ss"&gt;status: :ok&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When our API receives that request to &lt;code&gt;/dinguses/3&lt;/code&gt; and runs this controller action, the params hash contains the value of the dynamic part of the route indicated by the symbol &lt;code&gt;:id&lt;/code&gt; as a key-value pair. The symbol is just a placeholder; the actual value for that placeholder from the request becomes the value, while the symbol becomes the key: &lt;code&gt;{id: '3'}&lt;/code&gt;. That's why we can access it with bracket notation in our controller's &lt;code&gt;#show&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;This works the same way in other methods for accessing a particular record by its &lt;code&gt;id&lt;/code&gt;, like &lt;code&gt;#update&lt;/code&gt; (for &lt;code&gt;PATCH&lt;/code&gt; requests) and &lt;code&gt;#destroy&lt;/code&gt; (for &lt;code&gt;DELETE&lt;/code&gt; requests).&lt;/p&gt;

&lt;h3&gt;
  
  
  Using the Params Hash with Request Bodies
&lt;/h3&gt;

&lt;p&gt;The other face of the params hash is revealed when our API receives a request with information in its body, like a &lt;code&gt;POST&lt;/code&gt; or &lt;code&gt;PATCH&lt;/code&gt; request.&lt;/p&gt;

&lt;p&gt;Say our frontend has a form so a user can create a new dingus and add it to our database. When they submit that form, the frontend performs a &lt;code&gt;fetch&lt;/code&gt; request like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://www.dingusdomain.com/dinguses&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;method&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;POST&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Content-Type&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;application/json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="na"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;stringify&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Spade's Obsession&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;magnitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;
  &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The body of that &lt;code&gt;POST&lt;/code&gt; request contains the information our API needs to create a new instance of the &lt;code&gt;Dingus&lt;/code&gt; model and save it to the database. Conveniently, that information will end up as tidy key-value pairs in the params hash, which we can access in our controller:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="c1"&gt;# in config/routes.rb&lt;/span&gt;
&lt;span class="n"&gt;post&lt;/span&gt; &lt;span class="s1"&gt;'/dinguses'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;to&lt;/span&gt; &lt;span class="s1"&gt;'dinguses#create'&lt;/span&gt;

&lt;span class="c1"&gt;# in DingusesController&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;create&lt;/span&gt;
  &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="no"&gt;Dingus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="ss"&gt;name: &lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:name&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="ss"&gt;magnitude: &lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:magnitude&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="p"&gt;),&lt;/span&gt;
  &lt;span class="ss"&gt;status: :created&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note:&lt;/strong&gt; This very simplistic way of writing this controller action does work, but we're only using it for the sake of example. It's much better to write a private method for &lt;strong&gt;strong params&lt;/strong&gt; and use &lt;strong&gt;mass assignment&lt;/strong&gt; in actions like &lt;code&gt;#create&lt;/code&gt;... but that's a topic for another time.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Double Your Params, Double Your Fun
&lt;/h3&gt;

&lt;p&gt;Finally, the params hash can provide &lt;em&gt;both&lt;/em&gt; dynamic route information and request body information in the case of a &lt;code&gt;PATCH&lt;/code&gt; request.&lt;/p&gt;

&lt;p&gt;Consider the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="c1"&gt;# in config/routes.rb&lt;/span&gt;
&lt;span class="n"&gt;patch&lt;/span&gt; &lt;span class="s1"&gt;'/dinguses/:id'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;to&lt;/span&gt; &lt;span class="s1"&gt;'dinguses#update'&lt;/span&gt;

&lt;span class="c1"&gt;# in DingusesController&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;update&lt;/span&gt;
  &lt;span class="n"&gt;dingus&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;Dingus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:id&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
  &lt;span class="n"&gt;dingus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;magnitude: &lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:magnitude&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
  &lt;span class="n"&gt;render&lt;/span&gt; &lt;span class="ss"&gt;json: &lt;/span&gt;&lt;span class="n"&gt;dingus&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;status: :accepted&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we have a dynamic endpoint for requests to update a specific dingus. Like the example &lt;code&gt;#show&lt;/code&gt; method above, the &lt;code&gt;#update&lt;/code&gt; method in our controller gets the actual value of &lt;code&gt;:id&lt;/code&gt; from the params hash and uses it to retrieve the matching record from the database. Then it &lt;em&gt;also&lt;/em&gt; accesses the params hash to get information from the body of the &lt;code&gt;PATCH&lt;/code&gt; request (in this case just changing the value of the &lt;code&gt;magnitude&lt;/code&gt; attribute).&lt;/p&gt;

&lt;h3&gt;
  
  
  Params Demystified
&lt;/h3&gt;

&lt;p&gt;The params hash has even more uses than what we've outlined here (like containing &lt;strong&gt;query string parameters&lt;/strong&gt;), but these two cases are the most basic. Knowing how it carries dynamic route information and request body information, and how to access each kind in your controller actions, is fundamental to implementing typical RESTful routing in a Rails API. With those two essential uses clarified, hopefully this multivarious little data collection is a bit less of a mystery.&lt;/p&gt;

</description>
      <category>rails</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Self Exploration: Self in Ruby Class and Instance Methods</title>
      <dc:creator>Martin Souza</dc:creator>
      <pubDate>Wed, 07 Dec 2022 04:28:08 +0000</pubDate>
      <link>https://forem.com/souzamartin/self-exploration-self-in-class-and-instance-methods-in-ruby-29i1</link>
      <guid>https://forem.com/souzamartin/self-exploration-self-in-class-and-instance-methods-in-ruby-29i1</guid>
      <description>&lt;p&gt;In learning Ruby and Active Record over the past couple weeks, I found &lt;code&gt;self&lt;/code&gt; one of the most useful yet also most potentially confusing tools in the language. Figuring out how to correctly use &lt;code&gt;self&lt;/code&gt; can become especially tricky depending on whether you're writing class methods or instance methods—so in this post, we'll walk through how &lt;code&gt;self&lt;/code&gt; works in each situation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Knowing Thine Self
&lt;/h3&gt;

&lt;p&gt;First off, it helps to know what &lt;code&gt;self&lt;/code&gt; is in general. In Ruby, &lt;code&gt;self&lt;/code&gt; is a keyword that can refer to different things depending on the &lt;strong&gt;context&lt;/strong&gt; in which you use it. Calling &lt;code&gt;self&lt;/code&gt; returns the &lt;strong&gt;current object&lt;/strong&gt;—but what that object is, &lt;em&gt;i.e.&lt;/em&gt; the &lt;strong&gt;value&lt;/strong&gt; of &lt;code&gt;self&lt;/code&gt;, varies. This is exactly why it can be hard to keep track of what &lt;code&gt;self&lt;/code&gt; means in any given situation.&lt;/p&gt;

&lt;p&gt;For our purposes, we'll focus on how to use &lt;code&gt;self&lt;/code&gt; in class and instance methods, and how it behaves differently in each. Also, while we'll look at Active Record model classes as examples here, the specific behavior of &lt;code&gt;self&lt;/code&gt; and the overall concepts are applicable to Ruby classes in general.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note:&lt;/strong&gt; Remember that by convention, documentation and other writing about Ruby differentiates class and instance methods by representing them with different punctuation. Class methods are referred to as they actually appear when invoked in code, with dot notation: &lt;code&gt;ClassName.class_method_name&lt;/code&gt;. However, instance methods are shown with an octothorpe &lt;code&gt;#&lt;/code&gt; in place of the dot: &lt;code&gt;instance_name#instance_method_name&lt;/code&gt;. Just remember that in actual code they're both invoked with dot notation.&lt;/em&gt; &lt;/p&gt;

&lt;h3&gt;
  
  
  Self in Instance Methods
&lt;/h3&gt;

&lt;p&gt;Let's begin with instance methods, where &lt;code&gt;self&lt;/code&gt; is the most straightforward. Say we have a class (in this case, an Active Record model) like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Dingus&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
  &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:things&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;count_things&lt;/span&gt;
    &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;things&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;size&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our instance method &lt;code&gt;#count_things&lt;/code&gt; returns the number of things that belong to the instance of &lt;code&gt;Dingus&lt;/code&gt; &lt;strong&gt;on which we call &lt;code&gt;#count_things&lt;/code&gt;&lt;/strong&gt;. That last part is key: because &lt;code&gt;#count_things&lt;/code&gt; is an instance method, we'll always call it on a particular instance of the &lt;code&gt;Dingus&lt;/code&gt; class—and that specific instance is what &lt;code&gt;self&lt;/code&gt; refers to in the context of the method.&lt;/p&gt;

&lt;p&gt;Thus if &lt;code&gt;Dingus&lt;/code&gt; instance &lt;code&gt;d1&lt;/code&gt; happens to have 10 &lt;code&gt;Thing&lt;/code&gt; instances associated with it, and &lt;code&gt;Dingus&lt;/code&gt; instance &lt;code&gt;d2&lt;/code&gt; has 20, the return values of &lt;code&gt;d1.count_things&lt;/code&gt; and &lt;code&gt;d2.count_things&lt;/code&gt; will be 10 and 20, respectively.&lt;/p&gt;

&lt;p&gt;In instance methods, the &lt;code&gt;self&lt;/code&gt; keyword is extremely useful. The example above only illustrates it in terms of basic Active Record association functionality, but it enables you to access any attribute of the instance, as well as any other instance methods the class has, inside the execution context of an instance method.&lt;/p&gt;

&lt;h3&gt;
  
  
  Self in Class Methods
&lt;/h3&gt;

&lt;p&gt;Class methods are where &lt;code&gt;self&lt;/code&gt; tends to become more potentially confusing. First of all, the keyword &lt;strong&gt;must be used in the definition of a class method&lt;/strong&gt;, like this one added to our &lt;code&gt;Dingus&lt;/code&gt; class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Dingus&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="no"&gt;ActiveRecord&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;Base&lt;/span&gt;
  &lt;span class="n"&gt;has_many&lt;/span&gt; &lt;span class="ss"&gt;:things&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;count_things&lt;/span&gt;
    &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;things&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;size&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nc"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;has_most&lt;/span&gt;
    &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sort_by&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;dingus&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;dingus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;count_things&lt;/span&gt;&lt;span class="p"&gt;}.&lt;/span&gt;&lt;span class="nf"&gt;last&lt;/span&gt;
  &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This class method &lt;code&gt;.has_most&lt;/code&gt; iterates over every instance of the &lt;code&gt;Dingus&lt;/code&gt; class and sorts them in order of how many &lt;code&gt;Thing&lt;/code&gt;s they have by calling &lt;code&gt;#count_things&lt;/code&gt; on each one. Finally, it returns the last instance of &lt;code&gt;Dingus&lt;/code&gt; from that sorted collection, which will be the one with the most &lt;code&gt;Thing&lt;/code&gt; instances because the sort order is ascending by default.&lt;/p&gt;

&lt;p&gt;We can immediately tell &lt;code&gt;.has_most&lt;/code&gt; is a class method because it has &lt;code&gt;self&lt;/code&gt; in the definition. This is simply the necessary syntax to define a class method, but it also makes sense: in the execution context of the class, &lt;code&gt;self&lt;/code&gt; refers to the class itself.&lt;/p&gt;

&lt;p&gt;Moreover, within the class method, &lt;code&gt;self&lt;/code&gt; &lt;strong&gt;still refers to the class&lt;/strong&gt;, not any particular instance thereof. Thus, in this class method, &lt;code&gt;self.all&lt;/code&gt; is equivalent to &lt;code&gt;Dingus.all&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  TLDR
&lt;/h3&gt;

&lt;p&gt;Most simply put, just remember: &lt;em&gt;Inside instance methods, &lt;code&gt;self&lt;/code&gt; refers to the specific instance the method is called on.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Meanwhile, &lt;code&gt;self&lt;/code&gt; is &lt;em&gt;used in the definition of class methods&lt;/em&gt;, &lt;strong&gt;and&lt;/strong&gt; &lt;em&gt;inside class methods, &lt;code&gt;self&lt;/code&gt; refers to the class itself&lt;/em&gt;, not any particular instance.&lt;/p&gt;

&lt;p&gt;Keep these distinctions in mind, and it'll be much clearer when and how to use &lt;code&gt;self&lt;/code&gt; in different situations.&lt;/p&gt;

</description>
      <category>watercooler</category>
    </item>
    <item>
      <title>Single-Handedly Handling React Forms</title>
      <dc:creator>Martin Souza</dc:creator>
      <pubDate>Thu, 17 Nov 2022 16:37:57 +0000</pubDate>
      <link>https://forem.com/souzamartin/single-handedly-handling-react-forms-4la5</link>
      <guid>https://forem.com/souzamartin/single-handedly-handling-react-forms-4la5</guid>
      <description>&lt;p&gt;Like most other things it offers, React provides a streamlined way to implement forms. Not only does the declarative syntax of JSX make building forms easier, but by leveraging state in combination with form elements, React allows us to control our forms' inputs. This enables easy collection of input data as well as other useful wizardry like input validation.&lt;/p&gt;

&lt;p&gt;However, in learning how to make controlled forms with React, I found there's a sizable leap from the basics of setting up form inputs, each connected to its own independent state variable and each with a separate handler function, to the much more elegant and slick technique of using a single state variable and one handler function to manage an entire form. In this post, I'll walk through how to set up that trick.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note:&lt;/strong&gt; This post assumes familiarity with the concept of controlled inputs and how to build a basic form in React.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For a very small form with just a couple of inputs, having a separate state variable and change handler function for each input isn't that much trouble. The more inputs you have, though, the more unwieldy your code becomes—and fast. If each input in our form component is set up like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;formNameInput&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setFormNameInput&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleNameInput&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;setFormNameInput&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;form&lt;/span&gt; &lt;span class="na"&gt;onSubmit&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleSubmit&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;input&lt;/span&gt; 
      &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"text"&lt;/span&gt;
      &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;formNameInput&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;onChange&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleNameInput&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
    // ...
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;form&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;...We'll accumulate a large collection of state variables and state setter functions. We could cut some lines of code by invoking each input's respective setter function in-line inside the &lt;code&gt;onChange&lt;/code&gt;, rather than writing individual handler functions, but even so the code for managing our form data will rapidly get out of hand. We can avoid this entire headache by using a single state variable to hold all our form data and one handler function that can tell which input it's being called from, and can accordingly update the right part of the form data in state.&lt;/p&gt;

&lt;h3&gt;
  
  
  Objectify Your Data
&lt;/h3&gt;

&lt;p&gt;The key to this (pun intended) is to store all our form data in an object, rather than in separate pieces. Let's say our form has three inputs: name, description, and number. We can initialize one state variable and keep all three pieces of data there inside an object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;formData&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setFormData&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;description&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;number&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we invoke &lt;code&gt;useState&lt;/code&gt;, we set its initial value to an object with keys that match our form's inputs (more on that later), and assign each key a default value (empty strings for name and description, and 0 for number).&lt;/p&gt;

&lt;p&gt;As an aside, we could save this object to a separate variable, and use that to set our initial state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;initialFormState&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;description&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;number&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;formData&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setFormData&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;initialFormState&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This isn't necessary, but it might look a little neater. It also comes in handy for resetting the form later.&lt;/p&gt;

&lt;h3&gt;
  
  
  Input Names are Valuable
&lt;/h3&gt;

&lt;p&gt;The second key part (strained pun still intended) of our setup is giving each of our form inputs a &lt;code&gt;name&lt;/code&gt; attribute &lt;strong&gt;that exactly matches the corresponding key&lt;/strong&gt; in the &lt;code&gt;formData&lt;/code&gt; object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;form&lt;/span&gt; &lt;span class="na"&gt;onSubmit&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleSubmit&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;input&lt;/span&gt; 
      &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"text"&lt;/span&gt;
      &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;formData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;
      &lt;span class="na"&gt;onChange&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleInput&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;input&lt;/span&gt; 
      &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"textarea"&lt;/span&gt;
      &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;formData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;description&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"description"&lt;/span&gt;
      &lt;span class="na"&gt;onChange&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleInput&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;input&lt;/span&gt; 
      &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"number"&lt;/span&gt;
      &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;formData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"number"&lt;/span&gt;
      &lt;span class="na"&gt;onChange&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleInput&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;input&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"submit"&lt;/span&gt; &lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;form&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;This is essential!&lt;/em&gt; Each input element &lt;strong&gt;must&lt;/strong&gt; have a &lt;code&gt;name&lt;/code&gt; attribute with a value &lt;strong&gt;exactly the same&lt;/strong&gt; as one of the keys in the &lt;code&gt;formData&lt;/code&gt; object. These matching &lt;code&gt;name&lt;/code&gt; attributes are how our single handler function will be able to know which key/value pair to update in &lt;code&gt;formData&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Note also that we're now setting the &lt;code&gt;value&lt;/code&gt; attribute of each input with a reference to the corresponding key in the &lt;code&gt;formData&lt;/code&gt; object.&lt;/p&gt;

&lt;h3&gt;
  
  
  Handling It All
&lt;/h3&gt;

&lt;p&gt;With our &lt;code&gt;formData&lt;/code&gt; object in a single state variable and our controlled inputs given matching &lt;code&gt;name&lt;/code&gt; attributes, we can finally write our handler function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleInput&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;nameInput&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;valueInput&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;

  &lt;span class="nx"&gt;setFormData&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;formData&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;nameInput&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt; &lt;span class="nx"&gt;valueInput&lt;/span&gt;
  &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's break down what's going on here. First of all, notice we're still passing in the event object from whichever &lt;code&gt;onChange&lt;/code&gt; invokes the function. Then we pull two pieces of information out of that event object, and assign them to variables: the &lt;code&gt;name&lt;/code&gt; attribute of the input element from which &lt;code&gt;handleInput&lt;/code&gt; was invoked, and the value the user has just entered into that input, which triggered the &lt;code&gt;onChange&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Next, we invoke our state setter function &lt;code&gt;setFormData&lt;/code&gt; so we can update state with the newly entered information. Since our state variable &lt;code&gt;formData&lt;/code&gt; contains an object, we have to replace the whole object when we use the setter function to update it. Thus, we use the spread operator &lt;code&gt;...&lt;/code&gt; to copy the entire current contents of &lt;code&gt;formData&lt;/code&gt;, then specify which key/value pair to change in that copy using our variables &lt;code&gt;nameInput&lt;/code&gt; and &lt;code&gt;valueInput&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Note the square brackets around &lt;code&gt;nameInput&lt;/code&gt;. This is just the syntax required to interpolate a variable for the name of an object's key in this case. This detail tripped me up when I first learned to write this kind of handler function.&lt;/p&gt;

&lt;p&gt;Because we're pulling the &lt;code&gt;name&lt;/code&gt; attribute from the input element, and because we made sure that &lt;code&gt;name&lt;/code&gt; exactly matches a key in the &lt;code&gt;formData&lt;/code&gt; object, our handler function can use the &lt;code&gt;name&lt;/code&gt; attribute to specify which key/value pair to update with the state setter function. The other key/value pairs will remain unchanged—so whichever input the user interacts with, only that input's corresponding information in &lt;code&gt;formData&lt;/code&gt; will change. Our one function can handle every input element in our form, no matter how many we add.&lt;/p&gt;

&lt;p&gt;Finally, a further benefit of managing forms this way is that all your form information will already be packaged in a nice, neat object, ready to be taken in and passed on by your submit handler function. This obviates the work of building such an object from the data in separate state variables for each input element.&lt;/p&gt;

&lt;h3&gt;
  
  
  Smoothing Things Out
&lt;/h3&gt;

&lt;p&gt;We can refactor our single handler function to make it more compact. For one thing we could use a little object destructuring to simplify the variable assignment part:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleInput&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;

  &lt;span class="nx"&gt;setFormData&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;formData&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt;
  &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we're just taking &lt;code&gt;e.target.name&lt;/code&gt; and &lt;code&gt;e.target.value&lt;/code&gt; and assigning them to variables &lt;em&gt;also&lt;/em&gt; called &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;value&lt;/code&gt;, then using those in the state setter function as before.&lt;/p&gt;

&lt;p&gt;However, we can still do one better, and eliminate the variable assignment entirely:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleInput&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;setFormData&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;formData&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;
  &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Turns out we don't even need those helper variables! Our handler function can just invoke the state setter function and directly use the &lt;code&gt;name&lt;/code&gt; attribute and input value from the event object.&lt;/p&gt;




&lt;p&gt;React makes forms pretty easy, but there's definitely a pronounced learning curve to go from the basic idea of connecting each input element to its own state to managing a whole form with one piece of state and one handler function, no matter how many inputs it has. However, not only is it worth doing so simply to make your code less cumbersome, but ultimately this approach is all but necessary to deal with forms with more than a tiny number of inputs.&lt;/p&gt;

&lt;p&gt;Hopefully walking through each step of how to set up a React form like this helps you make that level-up.&lt;/p&gt;

</description>
      <category>react</category>
      <category>beginners</category>
      <category>tutorial</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Connecting Things in React</title>
      <dc:creator>Martin Souza</dc:creator>
      <pubDate>Mon, 07 Nov 2022 18:17:05 +0000</pubDate>
      <link>https://forem.com/souzamartin/connecting-things-in-react-4o66</link>
      <guid>https://forem.com/souzamartin/connecting-things-in-react-4o66</guid>
      <description>&lt;p&gt;When I first read the official documentation as a preliminary to studying React in earnest, I quickly became dismayed. HTML-looking elements commingling amidst JS? This ubiquitous props object, which comes from where? The mysteriously recorded information kept in state, necessary for dynamic behavior—but how? And on top of all of this, the new overarching concept of information flow across a component hierarchy! I closed the React docs without making it to the end.&lt;/p&gt;

&lt;p&gt;However, after my head stopped spinning, I found at least one thing had made sense: components—or rather, the idea of modularity. As I started actually studying each piece of React and learning its declarative syntax, I began to form an analogy for how it all works, which ended up helping me immensely to wrap my mind around the basic concepts and how to use them to build things. If you're also having a hard time with React, maybe my analogy will help you too.&lt;/p&gt;

&lt;p&gt;It has to do with what it was like to set up old computer hardware like this:&lt;/p&gt;

&lt;p&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%2Fzdf7f0z1rzv3s0v42086.JPG" 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%2Fzdf7f0z1rzv3s0v42086.JPG" alt="Mac Plus, via Wikimedia Commons"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;My first computer, long ago, was a Mac Plus like that one (though I don't think I ever had one of those additional external floppy drives). The other hand-me-down computers I used afterward were similar desktop setups: a tower, a monitor, a keyboard, a mouse, maybe eventually a Wacom tablet or a Zip disc drive. Unlike the unitary laptop I use now, back then my computer as a whole system was cobbled together from physically separate pieces of hardware that had to be correctly connected to each other in order to function. Of course, before the advent of USB, that meant several different kinds of cables had to be matched with the right kinds of ports in the right places to successfully make those connections.&lt;/p&gt;

&lt;p&gt;Perhaps you already see where this is going: my old computer was a collection of &lt;em&gt;components&lt;/em&gt;, linked together by specific kinds of connections. When I starting thinking of React apps in the same way, visualizing React components as if they were physical pieces I had to plug into each other with the right figurative cables, it felt like the whole framework suddenly opened up to me.&lt;/p&gt;

&lt;h3&gt;
  
  
  A Series of Tubes
&lt;/h3&gt;

&lt;p&gt;Take props, for starters. At first, I struggled to understand how props were defined for any given component, and also how specific values were passed as props to a particular component instance. But it all became clear once I saw examples of destructured props. Say we have some child component like this in App.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;ChildComponent&lt;/span&gt; &lt;span class="na"&gt;firstProp&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;someValue&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt; &lt;span class="na"&gt;secondProp&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;anotherValue&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt; &lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I understood that we were passing &lt;code&gt;someValue&lt;/code&gt; and &lt;code&gt;anotherValue&lt;/code&gt; as props to our child component from its parent component, but I didn't understand how the connection worked until I saw the incoming props destructured in the child component like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;ChildComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="nx"&gt;firstProp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;secondProp&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;//...&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now it was as if I could see &lt;em&gt;both ends of the cable&lt;/em&gt;: each prop is like a wire I had to plug into the right 'port' of the component tag in the parent component, &lt;em&gt;and&lt;/em&gt; into the corresponding 'port' in the component declaration down the hierarchy in ChildComponent.js.&lt;/p&gt;

&lt;p&gt;It didn't matter that I didn't entirely understand how object destructuring works, or even that this was an example of that. I just accepted this was the applicable syntax, and understood that only with those figurative cables properly connected can the child component get the specified values of those props from its parent, and access those values with the specified variable references passed down to it.&lt;/p&gt;

&lt;p&gt;Once that much clicked, I retroactively understood what it meant if things were instead written like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;ChildComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;firstProp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;firstProp&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;secondProp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;secondProp&lt;/span&gt;
  &lt;span class="c1"&gt;//...&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without destructuring, it's as if the individual prop 'wires' are bundled together, enclosed inside a tube. We have to pull them out and connect each one individually to use them within the child component.&lt;/p&gt;

&lt;h3&gt;
  
  
  One Thing Leads to Another
&lt;/h3&gt;

&lt;p&gt;Having embraced this notion of plugging components into each other, the basic idea of state became much more easily comprehensible in turn. Say I have some state like this in a component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;isToggled&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setIsToggled&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Again, accepting this is just the syntax for setting things up (rather than worrying about how this clever array destructuring actually works when we initialize state like this), I thought about what's going on here as physically as possible: &lt;code&gt;isToggled&lt;/code&gt;, the state variable, is just a little container that holds some value I want to store (in this example, just a true/false Boolean). The setter function &lt;code&gt;setIsToggled&lt;/code&gt; is a convenient tool React provides for the sole purpose of changing the contents of that state variable container to whatever value we pass it.&lt;/p&gt;

&lt;p&gt;Within the component where this state is kept, I can connect whatever pieces I need to the state by having them use the setter function to change what's in the state variable, or by using a reference to the state variable to look at its current value. It's almost like another pair of little wires I can link up inside the component itself to create functionality—in this case probably a button that uses the setter function to toggle the value of the state variable between true and false, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;button&lt;/span&gt; &lt;span class="na"&gt;onClick&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nf"&gt;setIsToggled&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;isToggled&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;ON/OFF&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;button&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, it's as if I'm attaching a wire to my button to connect it to the state setter function, building a circuit that'll be completed when the &lt;code&gt;onClick&lt;/code&gt; event listener fires.&lt;/p&gt;

&lt;h3&gt;
  
  
  And Another Thing
&lt;/h3&gt;

&lt;p&gt;With the essentials of state in hand, I could combine it with my understanding of props as cables running between components to get a grip on the bizarre concept of inverse data flow. To expand upon our toggle example, what if the toggle button turns dark mode styling on and off for the whole page? In that case, the button itself might exist in a child component (like a navbar or a header), but we need to keep the &lt;code&gt;isToggled&lt;/code&gt; state higher up, in App.js, so we can use it to control which CSS is applied to everything in the App.&lt;/p&gt;

&lt;p&gt;With my understanding of props as cables to connect components together, I was finally able to understand how to pass down a handler function as a prop from the parent component App.js to the child component. That function would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleToggle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;setIsToggled&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;isToggled&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We'd pass it like any other prop, connecting both ends of the prop 'cable' in the parent component and the child component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Somewhere in the return of App.js:&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;ChildComponent&lt;/span&gt; &lt;span class="na"&gt;handleToggle&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleToggle&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt; &lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;

&lt;span class="c1"&gt;//Meanwhile, in ChildComponent.js:&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;ChildComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="nx"&gt;handleToggle&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;//...&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And finally, our revised button would be able to call the handler function in its event listener, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;button&lt;/span&gt; &lt;span class="na"&gt;onClick&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleToggle&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;ON/OFF&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;button&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we've passed &lt;code&gt;handleToggle&lt;/code&gt; as a prop, we can call it in the child component, but when we do, it runs at the level of the parent component where it's actually declared—and where it has access to the state setter function &lt;code&gt;setIsToggled&lt;/code&gt; to change the value we're storing in the state variable &lt;code&gt;isToggled&lt;/code&gt;. Passing a handler function as a prop in this way is like plugging in a special type of cable that allows us to send information back up the component hierarchy, unlike regular prop cables, which only carry information between components going down the hierarchy.&lt;/p&gt;




&lt;p&gt;All this is really basic stuff, but when I first started with React, the paradigm underlying the library and its whole approach to building a frontend was overwhelming at first—to say nothing of the unfamiliar syntax of JSX, functional components, props, and state. Finding a way to visualize React was the breakthrough that enabled me to understand these fundamentals. Once I found and plugged in that first figurative cable, the rest started coming much more easily. Now I feel I already have a decent grasp on how to build things with React, and I'm excited to see what I can do with it.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>beginners</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Hello W—</title>
      <dc:creator>Martin Souza</dc:creator>
      <pubDate>Sat, 05 Nov 2022 18:21:50 +0000</pubDate>
      <link>https://forem.com/souzamartin/hello-w--1lbj</link>
      <guid>https://forem.com/souzamartin/hello-w--1lbj</guid>
      <description>&lt;p&gt;I never liked that phrase, those two inescapable words every new programmer is instructed to use in their first &lt;code&gt;console.log&lt;/code&gt;, for their first function's return value, as the content of their first HTML element, or what have you.&lt;/p&gt;

&lt;p&gt;My earliest encounter with the immortal phrase came from my cousin, a childhood friend, always (and still) much more savvy and capable with tech than myself. I don't recall exactly when I first beheld the words, but presumably I saw them in some bit of programming my cousin showed me, probably when we were in middle school. Something about it always struck me as silly or frivolous in a way I found off-putting—though I never could put my finger on exactly why.&lt;/p&gt;

&lt;p&gt;Now, many years later, &lt;em&gt;I&lt;/em&gt; am the new programmer, typing those words myself as I begin to learn JavaScript, React, and other things in rapid succession at the Flatiron School. As I do, I can't help but feel that phrase take on new meaning for me. I'm acquiring new skills to take a new tack professionally, and in so doing I will re-introduce myself as something of a new person. Despite my lingering dislike for the phrase, I am indeed saying a new hello to the world.&lt;/p&gt;

&lt;p&gt;Or at least here I am saying hello to you.&lt;/p&gt;

&lt;p&gt;For the record, though, any test &lt;code&gt;console.log&lt;/code&gt; of mine will always say 'oink'.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>codenewbie</category>
    </item>
  </channel>
</rss>
