<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daisy Yi on Medium]]></title>
        <description><![CDATA[Stories by Daisy Yi on Medium]]></description>
        <link>https://medium.com/@pantomnesian?source=rss-5ba61c5da30d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EVtb8gpRIk86Xabk4TaUSA.png</url>
            <title>Stories by Daisy Yi on Medium</title>
            <link>https://medium.com/@pantomnesian?source=rss-5ba61c5da30d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:00:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pantomnesian/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Note to Self: Active Storage & Amazon S3]]></title>
            <link>https://medium.com/@pantomnesian/note-to-self-active-storage-amazon-s3-d2fb380457d7?source=rss-5ba61c5da30d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2fb380457d7</guid>
            <category><![CDATA[active-storage]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Daisy Yi]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 23:03:21 GMT</pubDate>
            <atom:updated>2023-10-11T07:24:25.693Z</atom:updated>
            <content:encoded><![CDATA[<p>Dear Self, just because you’ve done it once does not mean you will be able to do it again (as easily or the same way). When the time comes to try to use Active Storage again in a future project, I know you’ll come to the same starting point and go, “What the heck do I do?”</p><p>So this will be a guide with all the resources I’ve used gathered here for self future reference. I expect I will also update these steps and concepts accordingly when I try again and know better. At the end of this blog, in addition to my sources for this blog, there are extra links/resources attached that hold interesting pointers or steps I would like to try out next time.</p><p><strong>What is Active Storage?</strong></p><p>In official <a href="https://edgeguides.rubyonrails.org/active_storage_overview.html#setup">Rails Guide</a>, it states:</p><blockquote>Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.</blockquote><p>So this means we need to install Active Storage as well as utilize a cloud storage service. In my case, I will be using Amazon S3.</p><p><strong>First, Create Your AWS Account</strong></p><p>Here is the <a href="https://aws.amazon.com/s3/?did=ap_card&amp;trk=ap_card">link</a> to sign up. There is a free tier (“5 GB of S3 standard storage for 12 months”) and for my purposes, it was sufficient. It will still ask for your credit card info but you can set up a budget to control usage if you’re worried they’ll charge you.</p><p>Once you log in, you will have to 1) create a bucket, 2) create a user, then 3) configure these to your project.</p><p>So step 1. In AWS console, search for S3 and select it from the Services dropdown menu. Once you’re at the s3 Management Console, click on the yellow “Create Bucket” at the top right of the screen. It will take you to set up your bucket. Create a name and leave AWS Region as is. I left alone Object Ownership and Bucket Versioning to default, same for Block Public Access settings (where it should be at “Block all public access” if it isn’t). I added no tags and was advised to keep encryption off but there wasn’t that option, so again, I left it to default which was “Server-side encryption with Amazon S3 managed keys (SSE-S3)” for Encryption type. No word on Bucket Key so on default again (“Enable”). Bucket created!</p><p>Step 2. To create a user and thereby configure permissions on bucket. Click on main header Amazon 3 to get to console. Look up and select “IAM” from search console then once in IAMS dashboard, click on User at side panel. Click top right button that says “Create User.” Name user (I skipped the checkbox on providing user access to AWS Management Console) and hit Next. Click Next again since nothing was mentioned in the reference I was reading. Then I clicked Create User. I clicked on the newly created user and to the right of the Summary box for the user, I clicked the link to ‘Create access key. Next will turn up options for Access Key best practices and alternatives. I picked Local code because it seemed closest option then after confirming, I hit Next. Once I created the access key, I downloaded a .csv file because when I originally took a screenshot and guessed l’s for 1s and nothing worked, I had to go back and recreate a new access key. So a reliable copy of both will save time. Now, go to the Permissions tab under the Summary block. Click add Add Permissions (this could also have been done when first creating user but ah well) and click the third option ‘Attach policies directly’. In search bar, look us ‘S3’ then click checkbox for ‘AmazonS3FullAcess.’ Hit Next, then Add permission. Done for now!</p><p>Step 3. Configuration.</p><p>First, uncomment section starting with Amazon then fill in name of your bucket and region in config/storage.yml (if you don’t have this file, you will have to create one):</p><pre>amazon:<br>  service: S3<br>  access_key_id: &lt;%= Rails.application.credentials.dig(:aws, :access_key_id) %&gt;<br>  secret_access_key: &lt;%= Rails.application.credentials.dig(:aws, :secret_access_key) %&gt;<br>  region: us-east-2<br>  bucket: pet-gallery</pre><p>In config/environments/production.rb:</p><pre>config.active_storage.service = :amazon</pre><p>Apply to same line to config/environments/development.rb to use in development environment, and likewise, apply in production.rb for production environment (I think I did this to cover my bases but I’m not entirely sure if I needed to at the time).</p><p>Next, we’ll use Rail’s built-in encrypted credentials manager by first setting access key in credentials file. In terminal, run <em>EDITOR=vim bin/rails credentials:edit </em>to unencrypt and open the credentials file in Vim. it’s very likely you will already have Vim installed on your computer if you’re using Linux or Mac OS but if you’d like to check if you have it and what version, enter <em>vim — version</em> into terminal. If you have Windows, I believe you will have to install it first. Once you’re in Vim, press the ‘i’ key to go into insert mode and, here’s an instance where I screwed up and lost time, REMEMBER TO UNCOMMENT OUT the aws line, including the following access_key_id and secret_access_key lines. Erase placeholder values for both access_key_id and secret_access_key and replace them with the values from when you created a user. Then, hit Esc key to exit insert mode then type :wq then hit the enter key.</p><p><strong>Installation of Active Storage</strong></p><p>Start by adding the Active Storage gem to your Gemfile or installing it through your terminal via <em>active_storage:install. </em>Then run <em>rails db:migrate. </em>This will create the three tables (active_storage_blobs, active_storage_attachments, and active_storage_variant_records) that you need to use Active Storage. This <a href="https://dev.to/nemwelboniface/the-ultimate-guide-to-active-storage-in-rails-2f57#:~:text=Active%20Storage%20makes%20use%20of,the%20above%2Dmentioned%20three%20tables.">blog</a> covers those tables in detail.</p><pre>gem &#39;activestorage&#39;, &#39;~&gt; 7.0&#39;, &#39;&gt;= 7.0.4&#39;</pre><p>Nick Mendez from his <a href="https://dev.to/nickmendez/how-to-configure-active-storage-with-amazon-aws-s3-cloud-storage-h">blog</a> recommends installing Active Storage Validator to add validations to your Active Storage uploads. I did not but, future self, you may be inclined to try.</p><pre>gem &#39;activestorage-validator&#39;, &#39;~&gt; 0.2.2&#39;</pre><p><strong>Backend</strong></p><p>I had already created my models so I directly assigned the one-to-many relationships in the model files.</p><pre>class Pet &lt; ApplicationRecord<br>  has_many_attached :images<br>end</pre><p>(For the files being saved to ActiveStorage, I’ve seen them called <em>avatar(s), photograph(s), images(s). </em>You just name it then stick with it. )</p><p>Next, there’s a few things we need to add to the controller.</p><p>Add with_image_attached method and add :image to your strong parameters. If plural, you would change to .with_images.attached or images: [].</p><pre>def index<br>        pets = @current_user.pets.all.with_attached_images<br>        render json: pets, include: :user, status: :ok<br>end</pre><pre>def pet_params<br>        params.permit(:name, :breed, :description, :picture, :medical_needs, :dob, :notes)<br>end</pre><p>Then to the serializer, add Rails.application.routes.url_helpers and an images method. The method ensures that if files are attached to user account or pet, it will processes files to appropriate JSON to be rendered.</p><pre>class PetSerializer &lt; ActiveModel::Serializer<br>  include Rails.application.routes.url_helpers<br>  attributes :id, :name, :breed, :description, :picture, :medical_needs, :dob, :notes, :contacts, :image_urls<br>  <br>  has_many :contacts<br><br>  def images<br>    rails_blob_path(object.images, only_path:true) if object.images.attached?<br>  end<br><br>end</pre><p><strong>Frontend</strong></p><p>Take note to use javascript’s formData API(see example).</p><pre>function handlePostSubmit(e) {<br>        e.preventDefault();<br><br>        const formData = new FormData();<br>        formData.append(&#39;images&#39;, selectedImage)<br>        formData.append(&#39;id&#39;, id)<br>        <br>        fetch(`/pets/pic/${id}`, {<br>            method: &quot;PATCH&quot;,<br>            body: formData<br>        })<br>        .then((r) =&gt; {<br>            if (r.ok){<br>                r.json().then((r) =&gt; {<br>                    setPhotos(r.image_urls)<br>                })<br>            } else {<br>                r.json().then((err) =&gt; setErrors(err.errors))<br>            }<br>        })}<br><br>    }</pre><p><strong>Extra pointers:</strong></p><p>To delete, the code is:</p><pre>@current_user.images.purge</pre><p>This method below came useful to see if files were actually being uploaded to the cloud service.</p><pre>@current_user.images.attached?</pre><p>To add files:</p><pre>@current_user.images.attach(params[:images])</pre><p><strong>Sources + Extra Links</strong></p><p><a href="https://medium.com/@jedwardmook/uploading-multiple-files-using-rails-active-storage-and-react-219f07b5ac25">Uploading Multiple Files Using Rails Active Storage and React</a></p><p>The above blog is good for multiple attachments versus just attaching one image or avatar.</p><p><a href="https://medium.com/@taylor_8332/active-storage-aws-s3-and-render-a-step-by-step-setup-guide-fd77824bc010">Active Storage, AWS S3 and Render: A step-by-step setup guide</a></p><p>I somehow missed this blog when I was setting up but he’s impressively thorough having screenshots for every step. He did a few things differently, and his blog also has additional information for when deploying your project or website to Render. It should be a good reference to go over.</p><ul><li><a href="https://aws.amazon.com/s3/?did=ap_card&amp;trk=ap_card">Cloud Object Storage - Amazon S3 - Amazon Web Services</a></li><li><a href="https://guides.rubyonrails.org/active_storage_overview.html">Active Storage Overview - Ruby on Rails Guides</a></li><li><a href="https://www.honeybadger.io/blog/rails-app-aws-s3/">Using AWS S3 For File Storage in Rails Apps</a></li><li><a href="https://dev.to/nickmendez/how-to-configure-active-storage-with-amazon-aws-s3-cloud-storage-h">How to Configure Active Storage with Amazon AWS S3 Cloud Storage</a></li></ul><p><a href="https://dev.to/nemwelboniface/the-ultimate-guide-to-active-storage-in-rails-2f57#:~:text=Active%20Storage%20makes%20use%20of,the%20above%2Dmentioned%20three%20tables.">The Ultimate Guide to Active Storage in Rails</a></p><p><a href="https://medium.com/@andrewasmit/seed-data-with-image-attachments-via-activestorage-45c8516c19ea">Seed Data with Image Attachments</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2fb380457d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Note to Self: Exceptions]]></title>
            <link>https://medium.com/@pantomnesian/note-to-self-exceptions-c4738831befd?source=rss-5ba61c5da30d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4738831befd</guid>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Daisy Yi]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 19:04:39 GMT</pubDate>
            <atom:updated>2023-07-26T19:04:39.707Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What are exceptions?</strong></p><p>Exceptions are Ruby’s way of handling errors raised in a program. In the hierarchy of classes, Exception is the top level class that all other errors inherit from. Errors are typically an unwanted or unexpected events that disrupt the execution of a program and are handled by a rescue block. You ‘raise’ an exception and when you do, the program starts to shut down. And unless you figure out how to stop the process, the program will crash with an error message.</p><p>An exception’s code is enclosed in a begin/end block, ie.:</p><pre>begin<br>  unwanted or unexpected code<br>rescue<br>  # code to somehow ameliorate the error(s)<br>  damage_control()<br>end</pre><p>In the middle, you can see a rescue block to handle the begin or raised exception. When it’s used, it handles the exception and then execution of program continues. Besides “rescuing,” this is also called “handling” or “catching” an exception. Note that multiple clauses can be used in the same program meaning if an exception’s not handled by the first rescue clause, another rescue clause will most likely handle the exception. If an exception occurs outside the begin/end block or no rescue clause matches, Ruby will move up the stack and look for an exception handler in the caller.</p><p>There are a few statements or clauses one can use for your begin/end block: retry, raise, ensure, else.</p><p>Retry will execute the begin block from the beginning. If not too careful, it can also result in an infinite loop. The ensure clause will, well, ensure that some code will always be executed whether an exception is raised or not. The else clause will run if no exceptions are raised, and is positioned after any rescue clause and before any ensure.</p><pre>begin<br>   puts &quot;I&#39;m trying my best here&quot;<br>rescue Exception =&gt; e<br>   puts e.message<br>else<br>   puts &quot;Looking good so far, buddy!&quot;<br>ensure<br>   puts &quot;I will always ensure that I at least run&quot;<br>end</pre><p>Ruby provides the Exception class which contains its own methods. There are a hierarchy of 30 something classes with their own subclasses. One can also create subclasses of exceptions for the purpose of creating custom classes to provide additional information. You can check out the built-in subclasses of Exceptions here: <a href="https://ruby-doc.org/core-2.5.1/Exception.html">Ruby Doc on Exceptions.</a></p><p><strong>What are exception objects?</strong></p><p>They are regular Ruby objects that hold data about what raised an objection such as “its type (the exception’s class name), an optional descriptive string, and optional traceback information.”</p><p>Apparently, only a handful of internal Exceptions are used by Ruby. If curious, here are a list of very good examples: <a href="https://www.exceptionalcreatures.com/bestiary/Exception">Examples of Exception</a>. There it explains and gives examples of what various commonly used Exceptions mean, like LoadError (when a file required fails to load) or SyntaxError (error raised when program encounters invalid syntax).</p><p><strong>Important Tip</strong></p><p>Do not try to catch all exceptions. Rescuing all exceptions indiscriminately like this</p><pre>rescue Exception =&gt; e</pre><p>will put the exception object in ‘e,’ and by trying to catch all errors, one will hit some snags because many exceptions are reserved for use by Ruby internally. So to rescue all exceptions would also disable certain Ruby features required for normal execution. It is better practice to specify with the type(s) of exceptions.</p><pre>begin<br>  # ...<br>rescue ArgumentError =&gt; e<br>  puts &quot;Exception Class: #{ e.class.name }&quot;<br>  puts &quot;Exception Message: #{ e.message }&quot;<br>  puts &quot;Exception Backtrace: #{ e.backtrace }&quot;<br>rescue TypeError =&gt; e<br>  # ...more code<br>end</pre><p>Sources:</p><p><a href="https://ruby-doc.org/core-2.5.1/Exception.html">Ruby Doc on Exceptions</a></p><p><a href="https://www.geeksforgeeks.org/ruby-exception-handling/">Ruby | Exception Handling</a></p><p><a href="https://www.honeybadger.io/blog/a-beginner-s-guide-to-exceptions-in-ruby/">A Beginner’s Guide to Exceptions in Ruby</a></p><p><a href="https://stackify.com/rescue-exceptions-ruby/">How to Rescue Exceptions in Ruby</a></p><p><a href="https://www.exceptionalcreatures.com/bestiary/Exception">Exception</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4738831befd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Note to Self: Intro to Backend]]></title>
            <link>https://medium.com/@pantomnesian/not-to-self-intro-to-backend-cf2acedc39d5?source=rss-5ba61c5da30d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf2acedc39d5</guid>
            <category><![CDATA[sinatra-project]]></category>
            <dc:creator><![CDATA[Daisy Yi]]></dc:creator>
            <pubDate>Tue, 02 May 2023 06:02:17 GMT</pubDate>
            <atom:updated>2023-05-25T19:48:41.627Z</atom:updated>
            <content:encoded><![CDATA[<p>So, the most difficult part of Phase 3 is keeping track of what’s what and their relationship with each other. Obviously, this is nothing thorough or detailed about any of the subjects but I think it’s important to strengthen my grasp of the basic concepts since there was a lot of information in Phase 3. Here, I’m going to concern myself with mostly Ruby, SQL, Active Record, and Sinatra.</p><h4>What is Ruby?</h4><p>Ruby is an Object Oriented Programming (OOP) language, and bears some similarities with JavaScript. In Ruby, everything is object and is based off the real world. Objects have properties (as stored data in instance variables) and actions (in methods that define behavior).</p><p>Another type of programming is Procedural Programming (PP) where you build programs by sequential order. There are some advantages of OOP over PP, namely that in OOP, data security is prioritized, having its choice of public, protected, and public methods. OOP allows for inheritance, meaning different entities can have shared traits or behaviors inherited from a parent super class. Inheritance is useful because one can reuse code while no known feature exists is PP.</p><p>Something specific about inheritance is the :: operator or module namespacing which is a means to specify which methods are intended as class methods or instance methods. While inheritance &lt; syntax implies state is a type of class, like this:</p><pre>class Daisy&lt;Flower</pre><p>If :: syntax is used, Daisy::Flower gives the Daisy class access to all constants and instance methods without stating Daisy is a type of flower.</p><h4>What is SQL?</h4><p>SQL stands for Structured Query Language. It’s a language specifically used to communicate with databases and is used by many kinds of database systems like SQLite (which we are using for our Phase 3 project). SQLite itself is a relational database that stores data in a structure of tables and rows like in a spreadsheet. A few important things to note are that different databases have different datatypes available. SQLite uses five: null, text, integer, real, and blob. Another thing is that the database store representations of Ruby objects, not the Ruby objects themselves but only raw data describing the given Ruby objects.</p><h4>What is Active Record?</h4><p>Active Record is an ORM integrated as a Ruby gem to link Ruby to the database. ORM means Objective-Relational Mapping and is a technique or design pattern of accessing relational database using an object-oriented programming language like Ruby. We use ORM because it cuts out repetitive code and implements conventional patterns that are organized.</p><p>Active Record takes care of queries written in Ruby into commands that the database understands so that programmers don’t have to manually make changes to the database. It connects to the database, creates tables, finds and saves data.</p><h4>What is Sinatra?</h4><p>Sinatra is a small web framework that provides Domain Specific Language (DSL) implemented by Ruby. It’s Rack-based, lightweight, and flexible for building simple, dynamic Ruby applications. A web framework provides structure and libraries to create applications, and it handles request routing, provides a mechanism for apps to respond to different URLs with the appropriate response, and renders templates.</p><p>In the App class, we inherit routing DSL from Sinatra::Base.</p><p>We can easily send responses in more than one format, such as html or JSON for a frontend app like React using .to_json. Another benefit of Sinatra is the ability to define dynamic routes, using the params hash which gives us information from the URL.</p><pre>class ApplicationController &lt; Sinatra::Base<br>  set :default_content_type, &#39;application/json&#39;<br>  <br>  get &quot;/creators/:id&quot; do<br>    creator = Creator.find(params[:id])<br>    creator.to_json<br>  end<br>end</pre><h4>What is Rake?</h4><p>It’s a task management tool in Ruby to help automate certain tasks like executing SQL, migration, seeding, using console, and more that can all be executed from the command line.</p><p><strong>Sources:</strong></p><p><a href="https://byjus.com/gate/difference-between-procedural-and-object-oriented-programming/#:~:text=Procedural%20Programming%20divides%20the%20program,refers%20to%20them%20as%20objects.&amp;text=Available%20data%20is%20capable%20of,from%20one%20function%20to%20another.">Difference Between Procedural and Object Oriented Programming</a></p><p><a href="https://www.rubyguides.com/2017/08/how-does-sinatra-work/">A Quick Analysis of How Sinatra Work</a></p><p><a href="https://medium.com/swlh/breaking-down-a-sinatra-application-18d158ab80ea">Breaking Down A Sinatra Application</a></p><p><a href="https://www.w3schools.com/sql/sql_intro.asp">Introduction to SQL</a></p><p><a href="https://guides.rubyonrails.org/active_record_basics.html">Active Record Basics</a></p><p><a href="https://www.ruby-lang.org/en/documentation/quickstart/">Ruby in Twenty Minutes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf2acedc39d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Note to Self: Understanding State]]></title>
            <link>https://medium.com/@pantomnesian/note-to-self-react-state-a3ac3e3f5d18?source=rss-5ba61c5da30d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3ac3e3f5d18</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-usestate]]></category>
            <dc:creator><![CDATA[Daisy Yi]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 17:49:34 GMT</pubDate>
            <atom:updated>2023-01-14T01:21:11.014Z</atom:updated>
            <content:encoded><![CDATA[<p>At some point, you’re going to want to refresh your memory on State. Well, here’s the recap. Beware though, there are a few versions of React around with their own tutorials on state. What we’ve used thus far is React version 16.8.0.</p><p>This version uses React Hooks. Prior to this version, there were class components but since they’re fading in common usage, it’s on to the new!</p><h3>First: what is State?</h3><p>State is dynamic data that changes in your components through user interaction (in events such as submitting data in a form or clicking a counter button).</p><p>So how do we use state? To use state, we use an useState function from React which is a React Hook.</p><h3>What are React Hooks?</h3><p>React Hooks are functions that allow us to “hook” into React’s state and lifecycle features inside of our function components, and they tend to start with the prefix “use.” Users can also create their own custom Hooks but for now, we will be dealing with just useState, one of the most commonly used Hooks because it deals specifically with our topic here: state.</p><p>However, before moving on to useState, here are a few rules to know about Hooks:</p><ol><li>We can only call Hooks at the top level. This is because React relies on the order that Hooks are called to get the correct value. It also means that they cannot called inside loops, conditions, or nested conditions.</li><li>Hooks do not work in regular Javascript functions. You can only call Hooks from React functions.</li></ol><h3>How to use useState</h3><p>First, like with any other Hook, you must import useState.</p><pre>import React, { useState } from &#39;react&#39;;</pre><p>When we call useState, we are telling React to create a new internal state. useState will return an array with two variables inside of it: an initial value and a setter function that is to update state.</p><p>The easiest way to set up useState is by using the array destructuring syntax.</p><pre>const [count, setCount]= useState(0);</pre><p>The variable ‘count’ has the initial value which is 0, the parameter for useState. This parameter can be any type of data such as a number, (an empty) string, boolean, object, array, null, even a function to initialize a variable. This initial value will be assigned only at the first render of the component and in subsequent renders, React will ignore the useState Hook until the setter message takes a new value that updates the state variable, causing React to re-render. setMessage is the setter function, and setter functions generally have the prefix “set” as a common convention.</p><h3>the tricky stuff</h3><p>All this useState seems pretty simple but there are a few things that may throw a wrench into the works:</p><ol><li>Setter function does not update state immediately. It enqueues the update, waiting until after React finishes its render of the component. This is because useState sets state asynchronously, meaning it waits until React finishes renders the component to update state.</li><li>So in the example below, the first setCount is still 0 when it reaches the second setCount.</li></ol><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  function increment() {<br>    setCount(count + 1);<br>    setCount(count + 1);<br><br>    console.log(`surprise, it&#39;s: ${count}`);<br>  }<br><br>  return &lt;button onClick={increment}&gt;What&#39;s the actualcount: {count}&lt;/button&gt;;<br>}</pre><p>So the button will only update to 1 not 2 (and in the console.log, it will log as 0, having not rendered at all).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*i5agS72tBg6ZOQeG0vaA6Q.png" /></figure><p>To get around this, it’s recommended when working with values that are calculated based on using previous values of state like a counter to pass a callback function instead of just a new value. We can use the previous state, the state before the current call, in a callback function.</p><pre>function increment() {<br>    setCount((previousState) =&gt; previousState + 1);<br>    setCount((previousState) =&gt; previousState + 1);<br><br>    console.log(`surprise, it&#39;s: ${count}`);<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*pf3MZS-2HdN1Hk6dB1XD7w.png" /></figure><p>2. useState does not merge objects. Rather, React will replace the original state object, losing all other properties. To solve this, we would then use a spread operator or use multiple useState calls instead of a simple useState to store an object.</p><p>3. Another issue is with nested objects. You would have to use the spread operator multiple times to copy all other objects because the spread operator only makes shallow copies. It’s recommended to flatten your state objects as much by splitting the object into multiple state variables. And if that’s not possible, it’s worth looking into libraries such as immutable.js or immer.</p><h3>Sources:</h3><p><a href="https://www.w3schools.com/react/react_usestate.asp">W3School</a></p><p><a href="https://levelup.gitconnected.com/an-introduction-to-react-hooks-50281fd961fe">An Introduction to React Hooks</a></p><p><a href="https://blog.logrocket.com/a-guide-to-usestate-in-react-ecb9952e406c/#whatdoesthereactusestatehookdo">useState in React: A Complete Guide</a></p><p><a href="https://reactjs.org/docs/hooks-rules.html">React.js: Hooks Rules</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ac3e3f5d18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Note to Self: Scope]]></title>
            <link>https://medium.com/@pantomnesian/notes-to-self-scope-c07a1e198dae?source=rss-5ba61c5da30d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c07a1e198dae</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Daisy Yi]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 04:19:12 GMT</pubDate>
            <atom:updated>2022-11-04T04:24:48.722Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is scope?</strong></h3><p>The definition of scope is the scope of what values and expressions are available to reference. Anything outside of scope would be inaccessible and would result in ReferenceError.</p><h3><strong>Different Types of Scope</strong></h3><p>Javascript has a few different types of scope. At its most basic, there are global and local scopes.</p><p>Global is the default scope and is the outermost scope. Global variables can be accessed from everywhere in the code.</p><p>The local scopes are block and function scopes (you’ll see module scopes mentioned too). Function scope is created with a function and block scope is the scope within curly braces. Variables declared within a function or curly braces are local to that function or block. And, the parameter or argument entered into the function is also accessible as a variable.</p><p>A few things to note are that it’s recommended to declare variables locally when possible because global variables are said to take up more memory, and that issues arise when variables with the same names are declared separately within different scopes.</p><h3><strong>Keyword Declarations</strong></h3><p>Before ES6(2015), there was only the keyword var. Now there are two other JavaScript keywords: let and const (makes you wonder how wild the world of JS was prior to 2015).</p><p>Let and const are different from var in that they are block-scoped. Variables declared inside the curly braces cannot be accessed from outside of the block. Var is function scoped, meaning a code block does not create a scope for var but a function body does. In other words, even in a code block, var variables can be accessed outside that block. Observe:</p><pre>{<br>   var codeBlock = &#39;I know you can hear me&#39;<br>}</pre><pre>function codeFunction() {<br>   var codeFunction = &#39;I want my privacy&#39;;<br>}<br>console.log(codeBlock); // &#39;I know you can hear me&#39;<br>console.log(codeFunction); // <strong>ReferenceError</strong></pre><p>If a variable assigned to a value is not declared, it is automatically a global variable, regardless of where it is (ie. in a function scope).</p><h3><strong>if, for, while</strong></h3><p>If, for, while statements also create their own block scopes.</p><pre>{<br>   const codeBlock = &#39;Am I random or what?&#39;<br>}<br>console.log(codeBlock); // <strong>ReferenceError</strong></pre><h3>Nested Scopes</h3><p>To add to the subject’s complexity all the more, scopes can be nested. How? Well, if functions and code blocks can be nested inside other functions or code blocks, new scopes are created per code block. The rule of thumb for figuring out which variables are available is that inner scopes can reference variables and expressions in outer scopes but outer scopes cannot reference inner scopes.</p><pre>const globalScope = &#39;I&#39;m global&#39;;<br>function theFunction() {<br>   const outerScope = &#39;I&#39;m outer scope&#39;;<br>   console.log(innerScope); // <strong>ReferenceError</strong><br>   function nestedFunction() {<br>      const innerScope = &#39;I&#39;m inner scope&#39;;<br>      console.log(outerScope); // &#39;I&#39;m outer scope&#39;<br>      console.log(globalScope); // &#39;I&#39;m global&#39;<br>}<br>console.log(innerScope); // <strong>ReferenceError</strong><br>console.log(outerScope); // <strong>ReferenceError</strong></pre><p>You can see the innermost scope has access to its local variables and the variables from all the outer scopes. However, calling any of the variables in the inner nested function from the outside does not work.</p><h3>Lifetime of JavaScript Variables</h3><p>Interestingly enough, there is a post that mentions the lifetime of variables. I just assumed they exist forever in posterity but apparently not. Function or local variables are deleted once the function is completed and global variable are deleted once the browser window or tab is closed.</p><p>Sources:</p><p><a href="https://developer.mozilla.org/en-US/docs/Glossary/Scope">MDN</a></p><p><a href="https://www.w3schools.com/js/js_scope.asp">W3schools</a></p><p><a href="https://dmitripavlutin.com/javascript-scope/">https://dmitripavlutin.com/javascript-scope/</a></p><p><a href="https://www.freecodecamp.org/news/scope-and-closures-in-javascript/">https://www.freecodecamp.org/news/scope-and-closures-in-javascript/</a> *</p><p><a href="https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript">https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript</a></p><p><a href="https://www.programiz.com/javascript/variable-scope">https://www.programiz.com/javascript/variable-scope</a></p><p><a href="https://blog.bitsrc.io/understanding-scope-and-scope-chain-in-javascript-f6637978cf53">https://blog.bitsrc.io/understanding-scope-and-scope-chain-in-javascript-f6637978cf53</a></p><p><a href="https://blog.devgenius.io/understanding-scope-in-javascript-f88e946636ac">https://blog.devgenius.io/understanding-scope-in-javascript-f88e946636ac</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c07a1e198dae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Note to Self: what to use besides innerHTML]]></title>
            <link>https://medium.com/@pantomnesian/note-to-self-what-to-use-besides-innerhtml-9e00ab614ac0?source=rss-5ba61c5da30d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e00ab614ac0</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Daisy Yi]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 18:34:43 GMT</pubDate>
            <atom:updated>2022-10-22T01:30:03.491Z</atom:updated>
            <content:encoded><![CDATA[<p>I can’t count the number of times I’ve had to look up the differences between innerHTML, textContent, and innerText. Never mind that the words all sound the same too.</p><p>Anyway, for my sake, I’m going to pull all my scrambled notes into this one post. I probably will update this too because I feel like I always learn something new each time I look them up. And, mind you, these are findings over the internet so I can’t be certain that everything here is true or conclusive outside of certain points made on MDN. Some information will beget more questions, more wonky rabbit holes than I may prefer. But this is <em>my</em> resource even if it is less “polished.”</p><p>=====</p><p>First, we‘ll compare by visual differences. Here is our code:</p><pre>&lt;div id=&#39;example&#39;&gt;<br>   <br>I am getting &lt;b&gt;more and more&lt;/b&gt; confused     and would like some &lt;code&gt;hot cheetos&lt;/code&gt; but I would only suffer more, no?<br><br>&lt;/div&gt;<br><br>const getLearning = document.getElementById(&#39;example&#39;);</pre><p>.innerHTML</p><pre>getLearning.innerHTML<br><br>I am getting &lt;b&gt;more and more&lt;/b&gt; confused     and would like some &lt;code&gt;hot cheetos&lt;/code&gt; but I would only suffer more, no?</pre><p>.innerText</p><pre>getLearning.innerText<br><br>I am getting more and more confused and would like some hot cheetos but I would only suffer more, no?</pre><p>.textContent</p><pre>getLearning.textContent<br><br>I am getting more and more confused     and would like some hot cheetos but I would only suffer more, no?</pre><p>=====</p><p>.innerHTML</p><ul><li>Contains strings and all HTML (and XML) markup, spaces, line breaks included within.</li><li>However, innerHTML will return characters&amp;, &lt;, or &gt;, as &amp;amp;, &amp;lt;, and &amp;gt; respectively.</li><li>(An aside: apparently. you can insert HTML into the document versus replacing the contents of the element. Look up <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML">insertAdjacentHTML()</a>, dear future self.)</li><li>When one appends with .innerHTML, Javascript will reparse and recreate HTML elements, making it time-consuming (and thus, becoming quite consequential with larger and more complicated documents).</li><li>Honestly, I have found innerHTML to be the easiest to use in my Flatiron journey to manipulate DOM elements so far. However, innerHTML may cause a security risk. Users can inject malicious code into the website, a method called <a href="https://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting</a> (XSS). So it’s been recommended to use the other two.</li><li>Best for: Websites and sources you trust. When you want to see everything, including the string itself, HTML markup, any hidden styling, spacing, etc.</li></ul><p>.innerText</p><ul><li>Retrieves string and markups as plain text, or “human-readable” elements.</li><li>Takes CSS into account so creates a <a href="https://developer.mozilla.org/en-US/docs/Glossary/Reflow">reflow</a> when tracking if styles are up-to-date. This should be avoided because it is “computationally expensive.”</li><li>While .textContent and .innerText both remove the child nodes when altered, .innerText permanently destroys all descendant text nodes.</li><li>May exhibit some differences between browsers. Mr. Lister states in one of the Stack Overflow answers: “Mozilla ignores U+200E and U+200F characters (“lrm” and “rlm”) in innerText, while Chrome does not.”</li><li><strong>Best for:</strong> When you need to see what the content is without any formatting. I would consider this the “barest” or easiest to read of the three examples here.</li></ul><p>.textContent</p><ul><li>Retrieves content that is aware of script and style elements. But, will return or render spacing and line breaks (so no “&lt;br&gt;” or “span”).</li><li>Because .textContent is style-aware, it won’t show hidden text. In the MDN example, a string with a ‘style=&quot;display:none&quot;&#39;would not even come up.</li><li>.nodeValue has come up in my search as something similar to .textContent in that it is also relatively faster, doesn’t parse HTML, and retrieves plain text.</li><li>Works on most browsers but not on Internet Explorer 8 or earlier.</li><li><strong>Best for: </strong>When you need to see content plus styling. Gives you more than .innerText but not as much as .innerHTML. It seems to me that .textContent may be the preferable route over .innerText for most cases.</li></ul><p>=====</p><p>Sources:</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent">MDN: textContent</a></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText">MDN: innerText</a></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML">MDN: innerHTML</a></p><p><a href="https://betterprogramming.pub/dom-manipulation-the-dangers-of-innerhtml-602f4119d905">Dangers of innerHTML</a></p><p><a href="https://builtin.com/software-engineering-perspectives/innerhtml-vs-innertext">InnerText versus InnerHTML versus TextContent</a></p><p><a href="https://stackoverflow.com/questions/35213147/difference-between-textcontent-vs-innertext">Stack Overflow on InnerText versus TextContent</a></p><p>The <a href="http://perfectionkills.com/the-poor-misunderstood-innerText/">case for innerText</a> that I’d like to understand another day when I’m more experienced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e00ab614ac0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Note to Self: Do Not Panic]]></title>
            <link>https://medium.com/@pantomnesian/note-to-self-do-not-panic-75575695ccea?source=rss-5ba61c5da30d------2</link>
            <guid isPermaLink="false">https://medium.com/p/75575695ccea</guid>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[fears-and-anxieties]]></category>
            <category><![CDATA[personal]]></category>
            <dc:creator><![CDATA[Daisy Yi]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 19:03:43 GMT</pubDate>
            <atom:updated>2023-10-03T23:07:46.194Z</atom:updated>
            <content:encoded><![CDATA[<p>Because most likely, you will panic.</p><p>You will doubt yourself, thinking you’re too dumb, too undisciplined, too much of a lost cause to accomplish anything and that you, again, realized that too late. And, you will probably sabotage yourself when you feel your head hurting when you can’t comprehend your readings or labs. You would rather go take a nap or watch a show. You will definitely eat lots of junk food.</p><p>You need to learn, however, that your fears do not define you. Your body and mind seem to remember your failures pretty well but it also bears the muscle memory of all your hard work, too. You took the gamble even though you could hardly believe you could do it. But you knew you were afraid, and you knew you wanted to change that. You wanted yourself to learn now rather than later that fears are just fears. They can’t stop you.</p><p>Sure, you may fail. And that would be costly. But if you learn something, if you become better at learning and at dealing with your fears, it’s only the first step out of many.</p><p>Your efforts will be worth it because you are.</p><p>And knowing at least that, you will be fine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75575695ccea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>