<?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: pjparham</title>
    <description>The latest articles on Forem by pjparham (@pjparham).</description>
    <link>https://forem.com/pjparham</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%2F893974%2F5444de3c-930e-4c45-949d-9979f2f51ac7.png</url>
      <title>Forem: pjparham</title>
      <link>https://forem.com/pjparham</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/pjparham"/>
    <language>en</language>
    <item>
      <title>Rails Accepting Nested Parameters and Files</title>
      <dc:creator>pjparham</dc:creator>
      <pubDate>Wed, 08 Mar 2023 18:44:24 +0000</pubDate>
      <link>https://forem.com/pjparham/rails-accepting-nested-parameters-and-files-517i</link>
      <guid>https://forem.com/pjparham/rails-accepting-nested-parameters-and-files-517i</guid>
      <description>&lt;p&gt;Recently, I ran into a problem while programming my last project. I have a Recipe object that has_many Ingredient objects, and it also has an attached image. &lt;/p&gt;

&lt;p&gt;To get started with accepting nested parameters, I highly recommend checking out &lt;a href="https://dev.to/christiankastner/rails-strong-params-and-accepting-nested-parameters-5bgd"&gt;this article&lt;/a&gt; that does a great job at summing up Ruby's 'accepts_nested_attributes_for' macro to create multiple associated objects upon creation of your primary object. &lt;/p&gt;

&lt;p&gt;I had set my app up following that guide, and it was working perfectly. My recipe was getting created, along with all the associated ingredient objects. However, that was when I was sending the data via JSON. &lt;/p&gt;

&lt;h2&gt;
  
  
  JSON vs FormData
&lt;/h2&gt;

&lt;p&gt;JSON data does a great job at handling nested objects. The complexity came when I brought in passing an image file to Ruby from JavaScript. JSON does not allow you to send over full files. I had to use JavaScript's 'FormData' to send over the image file, but when I was passing in my other data to 'FormData' like I had with my JSON data, Ruby param's would show '[object Object]' as my params for 'ingredients_attributes'. This was an issue, and I had a hard time locating a working solution online. I found a solution that is not very complicated, so I am writing this article to share that here!&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript code to properly append nested data to FormData()
&lt;/h2&gt;

&lt;p&gt;I'm going to pair some of this down for simplicity's sake. Let's say we have a form that has the state of recipeName that points to a string and state of ingredients that points to an array of objects with the keys quantity, unit, and name. &lt;/p&gt;

&lt;p&gt;Inside our handle submit, we will begin by instantiating a recipe object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const recipe = {
name: recipeName,
ingredients_attributes: ingredients
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will then instantiate a the FormData variable and append the recipe's name like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const formData = FormData()
formData.append("name", recipe.name)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code is simple enough. I will now demonstrate how to append our ingredients attributes so that we are able to send as many ingredients objects as we need. We will be doing this using a forEach with index. Like I mentioned above, it is not a very complicated solution, but I had a hard time locating a solution online so I hope this can help someone else in their coding journey.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;recipe.ingredients_attributes.forEach((ingredient, index) =&amp;gt; {
  formData.append(`ingredients_attributes[${index}][quantity]`, ingredient.quantity;
  formData.append(`ingredients_attributes[${index}][unit]`, ingredient.unit;
  formData.append(`ingredients_attributes[${index}][name]`, ingredient.name;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So as you can see, when using form data we need to append each individual key value pair for Ruby to access the information properly. We can utilize the index in JavaScript's forEach to allow us to send as many nested objects as we'd like, iterating over the different key value pairs that we are expecting in our object. I will also add that in this specific form, quantity and unit were optional values for the user, so they always instantiated as an empty string to prevent any errors on our backend.&lt;/p&gt;

&lt;p&gt;I hope that this article helps you get over any bumps in your challenge. Happy coding!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Ruby on Rails relationships for models that join on multiple tables.</title>
      <dc:creator>pjparham</dc:creator>
      <pubDate>Mon, 09 Jan 2023 21:44:56 +0000</pubDate>
      <link>https://forem.com/pjparham/ruby-on-rails-relationships-for-models-that-join-on-multiple-tables-38c2</link>
      <guid>https://forem.com/pjparham/ruby-on-rails-relationships-for-models-that-join-on-multiple-tables-38c2</guid>
      <description>&lt;p&gt;Ruby on Rails offers many tools to link models in your database, sometimes so many that it can be confusing to find the correct solution for your problem. I recently had two models, User and Image, that joined on two tables, Reviews and Favorites. Finding the right solution for this issue took some leg work, but eventually I implemented a clean solution that worked just as I needed it to. Keep reading if you too want to discover how to handle models that join on multiple tables. &lt;/p&gt;

&lt;h2&gt;
  
  
  The problem
&lt;/h2&gt;

&lt;p&gt;I made a web app that had Users and Images. Users and Images both had many favorites and many reviews. Favorites are created when a user favorites an image, and reviews are created when a user reviews an image. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fi5vgt96slewexx5b4q1b.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fi5vgt96slewexx5b4q1b.jpg" alt="DB Layout" width="605" height="329"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I needed both my users to both access what images they have liked and what images they have favorited, and the reciprocal for my images.&lt;/p&gt;

&lt;p&gt;If I only had one joins table, I would achieve this relationship with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User &amp;lt; ApplicationRecord
has_many :images, through: :reviews
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, things start to look wrong when you add in the second relationship:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;has_many :images, through: :reviews
has_many :images, through: :favorites
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The solution
&lt;/h2&gt;

&lt;p&gt;Solving the above problem required me to search in a variety of places and was not the easiest to find, however the solution itself is very simple.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;has_many :reviewed_images, :through =&amp;gt; :reviews, :source =&amp;gt; :image
has_many :favorite_images, :through =&amp;gt; :favorites, :source =&amp;gt; :image
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows me to access the necessary data easily. &lt;/p&gt;

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

&lt;p&gt;Let's say I was playing around with this code in my Ruby console. If I set an instance of my user class equal to u1, I could call that user's favorite images with the syntax u1.favorite_images, and I could call their reviewed images with u1.reviewed_images. Pairing this access with my Controllers and Serializers, we can now send the nested data to the front end so our app operates the way we want it to. &lt;/p&gt;

</description>
      <category>vibecoding</category>
    </item>
    <item>
      <title>Quick Start guide to creating a table using Active Record</title>
      <dc:creator>pjparham</dc:creator>
      <pubDate>Sun, 20 Nov 2022 23:52:36 +0000</pubDate>
      <link>https://forem.com/pjparham/quick-start-guide-to-creating-a-table-using-active-record-333f</link>
      <guid>https://forem.com/pjparham/quick-start-guide-to-creating-a-table-using-active-record-333f</guid>
      <description>&lt;h1&gt;
  
  
  Object-Relational Mapping
&lt;/h1&gt;

&lt;p&gt;Object-Relational Mapping(ORM) is a technique that allows you to query and change data in a database using an object-oriented approach. When using an ORM, your classes will be database tables and instances of those classes will exist as rows in those tables. Using an ORM allows a developer to cut down on repetitive code while also implementing conventional, organized patterns. These practices keep a code base clean and readable, which is important especially when many developers will be working on the code.&lt;/p&gt;

&lt;p&gt;There are patterns that you will see when using an ORM that are worth taking note of. While classes are typically defined with a singular word, a class's corresponding table will be plural. If we have a &lt;code&gt;Book&lt;/code&gt; class, the corresponding table will be &lt;code&gt;books&lt;/code&gt;. Instances of the &lt;code&gt;Book&lt;/code&gt; class will be stored in the &lt;code&gt;books&lt;/code&gt; table as rows, and attributes for those instances will be stored in columns in the &lt;code&gt;books&lt;/code&gt; table. &lt;/p&gt;

&lt;h1&gt;
  
  
  Introducing Active Record
&lt;/h1&gt;

&lt;p&gt;Active Record is an ORM library that can be used with Ruby. Active Record comes with many built in methods that make it easier to manipulate our data. To use the Active Record gem in your code, you can simply run &lt;code&gt;gem install activerecord&lt;/code&gt; in your terminal, or by including it in your code's &lt;code&gt;Gemfile&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;To make use of Active Record's built-in ORM methods, we need to make our Ruby class a subclass of &lt;code&gt;ActiveRecord::Base&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;class Book &amp;lt; ActiveRecord::Base
end 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now our &lt;code&gt;Book&lt;/code&gt; class is able to talk to the &lt;code&gt;books&lt;/code&gt; table in the database. Something important to keep in mind when using Active Record is that Active Record follows &lt;strong&gt;convention over configuration&lt;/strong&gt;. This means that as long as you follow the conventions adopted by Active Record, you will need to write very little to no configuration for your models. It is &lt;strong&gt;very&lt;/strong&gt; important that your &lt;strong&gt;class names are singular and table names are plural&lt;/strong&gt;. As long as a developer follows this rule, Active Record can save developer's a lot of time and make their code much more readable. &lt;/p&gt;

&lt;h1&gt;
  
  
  Some useful methods from Active Record
&lt;/h1&gt;

&lt;p&gt;Making our Ruby classes subclasses of Active Record gives them access many methods. One very useful method is that &lt;code&gt;attr_accessors&lt;/code&gt; are usable with our code without having to explicitly write them in. I've defined some other useful methods from Active Record below, but I recommend any developer that is interested in using Active Record to read the &lt;a href="https://guides.rubyonrails.org/active_record_basics.html#convention-over-configuration-in-active-record"&gt;Active Record docs&lt;/a&gt; to see all that it can &lt;em&gt;really&lt;/em&gt; do. &lt;/p&gt;

&lt;h6&gt;
  
  
  &lt;code&gt;.column_names&lt;/code&gt;
&lt;/h6&gt;

&lt;p&gt;Retrieve a list of the columns in a table:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Book.column_names
#=&amp;gt; [:id, :name, :author, :genre]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  &lt;code&gt;.create&lt;/code&gt;
&lt;/h6&gt;

&lt;p&gt;Creates a new object for the class and saves the instance to the class's corresponding table&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Book.create(name: 'The Stranger', author: 'Albert Campus', genre: 'Philosophical novel')
# INSERT INTO books (name, author, genre) VALUES ('The Stranger', 'Albert Campus', 'Philosophical Novel') 
#=&amp;gt; #&amp;lt;Book: 0x00009f785d0832b0 id: 1, name: "The Stranger", author: "Albert Campus", genre: "Philosophical novel"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  &lt;code&gt;.all&lt;/code&gt;
&lt;/h6&gt;

&lt;p&gt;Return all the records from a table as instances of its class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Book.all
# SELECT "books".* FROM "books"
# =&amp;gt; [#&amp;lt;Book: 0x00009f785d0832b0 id: 1, name: "The Stranger", author: "Albert Campus", genre: "Philosophical novel"&amp;gt;]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  &lt;code&gt;.find&lt;/code&gt;
&lt;/h6&gt;

&lt;p&gt;Retrieve an object from the database by its &lt;code&gt;id&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;Book.find(1)
# SELECT "books".* FROM "books" WHERE "books"."id" = 1 LIMIT 1
#=&amp;gt; #&amp;lt;Book: 0x00009f785d0832b0 id: 1, name: "The Stranger", author: "Albert Campus", genre: "Philosophical novel"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  &lt;code&gt;.find_by&lt;/code&gt;
&lt;/h6&gt;

&lt;p&gt;Find an object by any attribute, such as &lt;code&gt;author&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;Book.find_by(author: 'Albert Campus')
# SELECT "books".* FROM "books" WHERE "books"."author" = 'Albert Campus' LIMIT 1
#=&amp;gt; #&amp;lt;Book: 0x00009f785d0832b0 id: 1, name: "The Stranger", author: "Albert Campus", genre: "Philosophical novel"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Active Record Migrations
&lt;/h1&gt;

&lt;p&gt;Active Record migrations are used to set up our database, and we use this format for many reasons. They provide a history of the changes made, providing version control for our database. Using Active Record migrations also allows us to forego writing SQL statements to create or change tables, as Active Record will do this for us under the hood. &lt;/p&gt;

&lt;p&gt;To tell Active Record how we want it to connect to our database, we will use a &lt;code&gt;config/database.yml&lt;/code&gt; file. This file is used by convention with Active Record to provide details about how to connect with our database. For this example, we will be using SQlite, but Active Record does support other database adaptors. This is what it looks like:&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

test:
  adapter: sqlite3
  database: db/test.sqlite3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's set up our &lt;code&gt;environment.rb&lt;/code&gt; file. This file requires the gems in our Gemfile to give our program access them them. &lt;code&gt;ENV["RACK_ENV"]&lt;/code&gt; is our &lt;strong&gt;environment variable&lt;/strong&gt;, which is set to development in this example. &lt;code&gt;RACK_ENV&lt;/code&gt; is a specific environment variable used by the &lt;code&gt;sinatra-activerecord&lt;/code&gt; gem to determine what database to connect to. Our &lt;code&gt;environment.rb&lt;/code&gt; file contains the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ENV["RACK_ENV"] ||= "development"

require 'bundler/setup'
Bundler.require(:default, ENV["RACK_ENV"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Creating a migration
&lt;/h3&gt;

&lt;p&gt;To create a migration to set up our books table, we will run the following command in our terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bundle exec rake db:create_migration NAME=create_books
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use bundle exec rake to access our rake file that gives us a multitude of commands that can be run in the terminal, and the above code is used to create a new migration. This command generates a new file in &lt;code&gt;db/migrations&lt;/code&gt; called &lt;code&gt;20221116095220_create_books.rb&lt;/code&gt;. The timestamp at the beginning is crucial for Active Record as it tells your program which order to run the migrations. The following code will be in the newly created file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CreateBooks &amp;lt; ActiveRecord::Migration[6.1]
  def change
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we are using this migration to create a new table, we will use the &lt;code&gt;create_table&lt;/code&gt; command to do so. When we create our table, we will provide the attribute names for the columns as well as the datatype for each of those columns. The id column is dynamically generated, so there is no need to include it here!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CreateBooks &amp;lt; ActiveRecord::Migration[6.1]
  def change
    create_table :books do |t|
      t.string :name
      t.string :genre
      t.string :author
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that the file is set up and you've defined how you want your table to look, we must run the migration! This will create a new database file based on the contents of your migration, and it will also create a &lt;code&gt;db/schema.rb&lt;/code&gt; file which will give you a quick view of the set up of your database. We run our migration with the following command in the terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bundle exec rake db:migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this stage, our &lt;code&gt;db/schema.rb&lt;/code&gt; file will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ActiveRecord::Schema.define(version: 2022_11_16_095220) do
  create_table "books", force: :cascade do |t|
    t.string "name"
    t.string "author"
    t.string "genre"
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it! The table now exists in the database with the columns that we have defined in our migration, as well as an id column. This is meant to serve as a brief guide to get started with Active Record migrations, but there is so much more that you can do using Active Record! Some of the most powerful use cases for Active Record involve creating &lt;a href="https://guides.rubyonrails.org/association_basics.html"&gt;associations&lt;/a&gt; between classes and tables. I encourage you to check out the resources below on Active Record Basics and Active Record associations to see all that Active Record can help you accomplish. Happy Coding!&lt;/p&gt;

&lt;h1&gt;
  
  
  Resources
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://guides.rubyonrails.org/active_record_basics.html"&gt;Active Record Basics&lt;/a&gt;&lt;br&gt;
&lt;a href="https://guides.rubyonrails.org/association_basics.html"&gt;Active Record Associations&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>activerecord</category>
    </item>
    <item>
      <title>PATCHing nested JSON data in a react application</title>
      <dc:creator>pjparham</dc:creator>
      <pubDate>Fri, 07 Oct 2022 18:06:29 +0000</pubDate>
      <link>https://forem.com/pjparham/patching-nested-json-data-in-a-react-application-2glm</link>
      <guid>https://forem.com/pjparham/patching-nested-json-data-in-a-react-application-2glm</guid>
      <description>&lt;p&gt;&lt;strong&gt;PATCHing nested JSON data&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Working with JSON data can be tricky, and when you are working with nested data it can be even trickier. Let's say that you are working with JSON data for posts on a site and each post has a nested array of comments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "posts": [
    {
      "id": 1,
      "title": "React 101",
      "subhead": "Some basics to get you started with React",
      "body": "React apps are build using components. These components are used to give you flexibility when writing code.",
      "user": "test",
      "comments": [
        {
          "id": 1,
          "text": "this is really good",
          "username": "Jose Ramirez"
        },
        {
          "id": 2,
          "text": "very helpful!",
          "username": "Jane Smith"
        }
      ]
    },
    {
      "id": 2,
      "title": "Using JSX",
      "subhead": "JSX basics",
      "body": "When writing your markup in react, you write it in JSX. This is very similar to HTML, but with some key differences. One difference to keep in mind is that JSX things expect a prop of className rather than class.",
      "user": "test",
      "comments": [
        {
          "id": 1,
          "text": "This is great.",
          "username": "John Doe"
        },
        {
          "id": 2,
          "text": "Thanks for this!",
          "username": "Kareena Bhatt"
        }
      ]
    },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your goal is to patch the comments. When working with nested data like this, we can pass in the key of "comments" so the data knows where to go. For the value, we first pass an array that has a value pointing to all the previous comments, then we can pass in our object with the new data. This is what a submit function could look like if you are trying to achieve this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function onSubmit(e){
        e.preventDefault()
        const newComment = {
            "comments": [
                ...allComments,
                {"text": commentText,
                "id": (commentCountRef.current),
                "username": (user.given_name + " " + user.family_name)}
            ]
        }
        fetch(`http://localhost:3004/posts/${post.id}`, {
            method: "PATCH",
            headers: {
                "Content-Type": "application/json"
        },
        body: JSON.stringify(newComment)
        })
        .then((r) =&amp;gt; r.json())
        .then((commentData) =&amp;gt; setAllComments(commentData.comments))
        commentCountRef.current += 1
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You then set your &lt;code&gt;allComments&lt;/code&gt; state with &lt;strong&gt;all&lt;/strong&gt; of the comment data. This is because this JSON request returns the &lt;em&gt;entire&lt;/em&gt; post object that it fetches. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Utilizing the useRef hook to get id values&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When dealing with data like this, another tricky thing is assigning your data the correct ID value. Although there are multiple ways to accomplish this, the useRef hook can be a useful tool and allows you to achieve this without having to import any additional packages. Let's break down how the useRef hook was used in this to assign the correct id value. &lt;/p&gt;

&lt;p&gt;Once you have imported the useRef hook to your application and set your current comments to state, you can set the useRef hook to hold the value of the length of your comments array and add one to it, thus equaling what our next id value should be.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    const commentCountRef = useRef(post.comments.length + 1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As seen above, this is passed into our object as the id. Now you are able to set the id of your new object and set the comments so that both your front-end and back-end technologies are updated when a new comment is submitted.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Adding Event Listeners and Understanding the DOM</title>
      <dc:creator>pjparham</dc:creator>
      <pubDate>Tue, 23 Aug 2022 15:16:35 +0000</pubDate>
      <link>https://forem.com/pjparham/adding-event-listeners-and-understanding-the-dom-2jeo</link>
      <guid>https://forem.com/pjparham/adding-event-listeners-and-understanding-the-dom-2jeo</guid>
      <description>&lt;h1&gt;
  
  
  What is the DOM?
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction"&gt;MDN docs&lt;/a&gt; defines the DOM as &lt;em&gt;the data representation of the objects that comprise the structure and content of a document on the web.&lt;/em&gt; In essence, it is the HTML that is actively being displayed on the web page. We can manipulate what is being displayed on the web page using various elements available in JavaScript by accessing the various nodes.&lt;/p&gt;

&lt;h1&gt;
  
  
  What is a node?
&lt;/h1&gt;



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

  &amp;lt;div&amp;gt;
    &amp;lt;p&amp;gt;Second&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code snipit above, we have multiple nodes. Everything between the body tags is a node, the contents of an individual div element are a node, and the individual p tags are also nodes that can be accessed and manipulated.&lt;/p&gt;

&lt;h1&gt;
  
  
  Finding an element on the page
&lt;/h1&gt;

&lt;p&gt;JavaScript has a few ways to find DOM nodes. Some of the methods that seem to get the most love are &lt;code&gt;document.querySelector()&lt;/code&gt;, &lt;code&gt;document.getElementById()&lt;/code&gt;, and &lt;code&gt;document.getElementsByClassName()&lt;/code&gt;. Other available methods include &lt;code&gt;document.getElementsByTagName()&lt;/code&gt; and &lt;code&gt;document.querySelectorAll()&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;document.getElementById() in action&lt;/strong&gt;&lt;br&gt;
This method allows us to easily grab a node by &lt;em&gt;grabbing&lt;/em&gt; it with the Id assigned to it.&lt;/p&gt;

&lt;p&gt;Imagine we have the following code:&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&amp;gt;
  &amp;lt;h1 id="heading"&amp;gt;This is the heading&amp;lt;/h1&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Javascript, we can access this element with the code &lt;code&gt;document.getElementById('heading')&lt;/code&gt;. It is often helpful to assign this a variable, which I will demonstrate here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const heading = document.getElementById('heading')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;the other methods in action&lt;/strong&gt;&lt;br&gt;
Given the following code, I will demo &lt;code&gt;document.getElementsByClassName&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;lt;div class="article-title"&amp;gt;
    &amp;lt;p&amp;gt;3 ways to spice up your dining room&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;

  &amp;lt;div class="article-title"&amp;gt;
    &amp;lt;p&amp;gt;What trends to expect this fall&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;

  &amp;lt;div class="article-title"&amp;gt;
    &amp;lt;p&amp;gt;You won't believe what this celebrity said...&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's say you want to grab all of the elements at the same time, and even assign them to a variable name that can be more easily accessed. We can do that with the single line of code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let articleTitles = document.getElementsByClassName('article-title')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Debugging tip!
&lt;/h4&gt;

&lt;p&gt;It is best practice to always console.log anytime you grab an element from the DOM. Some things can be tricky to grab, so it's always good to double check that the code is acting how you want it to before looking forward. Let's put all our previous code together to see that in action.&lt;br&gt;
Our HTML at this point looks like:&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&amp;gt;
  &amp;lt;h1 id="heading"&amp;gt;This is the heading&amp;lt;/h1&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div class="article-title"&amp;gt;
    &amp;lt;p&amp;gt;3 ways to spice up your dining room&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div class="article-title"&amp;gt;
    &amp;lt;p&amp;gt;What trends to expect this fall&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div class="article-title"&amp;gt;
    &amp;lt;p&amp;gt;You won't believe what this celebrity said...&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While our JavaScript, with our newly added console.logs, looks like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const heading = document.getElementById('heading')
let articleTitles = document.getElementsByClassName('article-title')
console.log(heading)
console.log(articleTitles)!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is what would be expected in the console if everything is working correctly: &lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4jC9cSms--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xsh5tp92uwmvf1toi3t9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4jC9cSms--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xsh5tp92uwmvf1toi3t9.png" alt="Console log of previous code" width="792" height="120"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  What is an event listener?
&lt;/h1&gt;

&lt;p&gt;The &lt;a href="https://www.w3schools.com/js/js_htmldom_eventlistener.asp"&gt;&lt;code&gt;addEventListener()&lt;/code&gt; method&lt;/a&gt; attaches an event handler to a specified element. &lt;code&gt;addEventListener()&lt;/code&gt; expects two arguments: the type of event we want to listen for and a callback function that will be called whenever our event listener 'hears' what we tell it to listen for. Some of the most common types of event listeners used are click, mouseover, and keydown.&lt;/p&gt;
&lt;h1&gt;
  
  
  So now that we can grab nodes, how do we add event listeners to them?
&lt;/h1&gt;

&lt;p&gt;It is most straightforward to add event listeners when we have assigned a variable name to an element we &lt;em&gt;grabbed&lt;/em&gt; by its ID, so for this part of the article we will be focusing on the variable we previously named heading after getting the heading element by its ID. Since we have declared a constant variable for heading, the syntax will be &lt;code&gt;heading.addEventListener()&lt;/code&gt;. But as previously mentioned, we must add the type of event we want to listen for and our callback function. For this demo we will be adding a click event listener to our page that simply displays a log in the console each time it is clicked.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;heading.addEventListener('click', () =&amp;gt; console.log('I was clicked!') )

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

&lt;/div&gt;



&lt;p&gt;Our callback function is inside of the event listener as an arrow function. If we were to simply write &lt;code&gt;heading.addEventListener('click', console.log('I was clicked!')&lt;/code&gt;, &lt;strong&gt;'I was clicked!'&lt;/strong&gt; would be in our console when we load the page, which would defeat the purpose of adding our event listener in the first place. If the event listener is added in properly, we should see the following in our console &lt;em&gt;after&lt;/em&gt; we click our heading:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--IyI8rksI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5biwfqxft75c9cv8ykpe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IyI8rksI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5biwfqxft75c9cv8ykpe.png" alt="Console with our newly added console log produced from our event listener" width="772" height="136"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our console log is displaying as expected! As you explore adding event listeners in your code, you will find that you can add &lt;em&gt;much&lt;/em&gt; more complicated functions as event listeners to create a highly interactive web page.&lt;/p&gt;
&lt;h2&gt;
  
  
  What about adding a function to our event listener?
&lt;/h2&gt;

&lt;p&gt;If you want to put a function that you defined somewhere else in your code into an event listener, you simply leave out the () which calls the function from the event listener.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sayHello(){
    console.log('Hello!')
};
heading.addEventListener("click", sayHello)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Debug tip
&lt;/h3&gt;

&lt;p&gt;I would encourage you to always put a console.log into event listeners when you first apply them to make sure it is responding how you want it to.&lt;/p&gt;

&lt;p&gt;I hope this article helped demystify what the DOM is and how to add event listeners to your code to actively manipulate the DOM. Happy coding!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Declaring Variables in JavaScript</title>
      <dc:creator>pjparham</dc:creator>
      <pubDate>Mon, 18 Jul 2022 15:17:38 +0000</pubDate>
      <link>https://forem.com/pjparham/declaring-variables-in-javascript-36f6</link>
      <guid>https://forem.com/pjparham/declaring-variables-in-javascript-36f6</guid>
      <description>&lt;p&gt;Hello! Welcome to my first post, and thank you for checking out my blog. We are going to start with something simple: the different ways to declare variables in JavaScript. &lt;/p&gt;

&lt;p&gt;There are three ways to declare variables in JavaScript, and those are let, const, and var. Today we will just be covering let and const, which were introduced in 2015 and are &lt;em&gt;now&lt;/em&gt; used much more often than var.&lt;/p&gt;

&lt;h2&gt;
  
  
  let
&lt;/h2&gt;

&lt;p&gt;Using let allows us to declare a variable that we may want to change the value of at a later time. You can declare a variable using let without immediately assigning it a value.&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;Later you could assign a value to your variable with the following syntax:&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;When using let, you can assign a different value to the variable at any time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dog;
//=&amp;gt; Ted
dog = 'Libby';
dog
//=&amp;gt; Libby
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  const
&lt;/h2&gt;

&lt;p&gt;We use const when we want to assign a value to a variable that will remain &lt;strong&gt;constant&lt;/strong&gt; throughout our code. You cannot reassign a variable declared with const, and its value &lt;em&gt;must&lt;/em&gt; be set when declaring the variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const breed = 'chihuahua';
//=&amp;gt;undefined

breed;
//=&amp;gt; chihuahua

breed = 'beagle'
//=&amp;gt; Uncaught TypeError: Assignment to constant variable.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you try to declare a variable using const without assigning a value, you will get an error message.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const breed
//=&amp;gt; Uncaught SyntaxError: Missing initializer in const declaration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope this helped you learn more about different ways to declare a variable in JavaScript, and  when to use let and when to use const. Thanks for reading!&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"&gt;MDN - let&lt;/a&gt;&lt;br&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"&gt;MDN - const&lt;/a&gt;&lt;/p&gt;

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