<?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 Molly McDonough on Medium]]></title>
        <description><![CDATA[Stories by Molly McDonough on Medium]]></description>
        <link>https://medium.com/@mcdonough.mollya?source=rss-f44f1d9da6f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mBhwdXewHFaxfN1e.</url>
            <title>Stories by Molly McDonough on Medium</title>
            <link>https://medium.com/@mcdonough.mollya?source=rss-f44f1d9da6f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:29:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mcdonough.mollya/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[Free Palestine]]></title>
            <link>https://medium.com/@mcdonough.mollya/free-palestine-7bf814881b2f?source=rss-f44f1d9da6f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bf814881b2f</guid>
            <category><![CDATA[humanism]]></category>
            <category><![CDATA[palestine]]></category>
            <category><![CDATA[gaza]]></category>
            <category><![CDATA[humanitarian]]></category>
            <dc:creator><![CDATA[Molly McDonough]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 16:15:16 GMT</pubDate>
            <atom:updated>2023-10-27T17:51:46.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Palestinean flag held up by a hand in front of a cloudy sky" src="https://cdn-images-1.medium.com/max/1024/1*swyD2zbSicYy3rIW_mHxWg.jpeg" /></figure><p>How do I make you care that innocent people are dying?<br>Do I show the wailing mothers?<br>The doctors appealing in eloquent language and white coats amidst a sea of rubble and corpses?<br>The dead babies with flies on their faces?<br>This is, the ones that still have faces.</p><p>Do I wear the right red lipstick to grab your attention?<br>Do I pepper in memes or cat pictures so I don’t lose you to my “politics”?<br>Do I use gentle appeals to call your representatives?<br>Or urgent words like genocide?</p><p>Do I berate you with facts?<br>Like thousands of civilians dead in weeks?<br>Or millions without food, water, or medical aid?</p><p>But you’ve heard that already.<br>And I need you to not reduce these people to “regrettable statistics”<br>To not erase them.<br>I need you to care about each mother who had to comfort their children as the bombs went off<br>not knowing if the next would come for them.<br>I need you to imagine how she distracted them as she wrote their names on their warm skin so their bodies could be identified.</p><p>I need you to think of those children.<br>Each child who had a favorite toy and a best friend from school that were buried under their homes together.<br>Each incredibly well-educated and civilized physician performing surgeries by cellphone light in the street without anesthesia.</p><p>I need you to hear the collective wails of grief that I’ve never heard in person<br>But I’ve felt in my chest every time someone I loved died.<br>I need you to care.</p><p>I need you to accept that genocide is preventable and it’s happening now.<br>To remember that our government, that every government, has power because we grant it.<br>Collectively, we are not helpless.</p><p>Together we can speak up, educate, donate, call our representatives, and take to the streets.<br>These atrocities demand not just attention, but action.<br>Together, we can stop this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf814881b2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Coding Bootcamp Experience]]></title>
            <link>https://medium.com/@mcdonough.mollya/my-coding-bootcamp-experience-390f39b94326?source=rss-f44f1d9da6f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/390f39b94326</guid>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Molly McDonough]]></dc:creator>
            <pubDate>Wed, 04 May 2022 16:26:27 GMT</pubDate>
            <atom:updated>2022-05-04T16:26:27.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="math lady meme- a confused looking with woman with geometric equations in front of her face" src="https://cdn-images-1.medium.com/max/681/0*JxH6NQhRPmPN3UZ1.jpg" /></figure><p>I first heard of coding bootcamps a number of years ago. A few of my friends decided after college that they weren’t happy with the current state of their careers and enrolled in them. I had neither the time nor money to essentially take and pay for another semester of school rather than working so I didn’t think much about them. Plus, my career was going well on paper. I was working for a financial software company and while the work wasn’t particularly intellectually or morally stimulating; I was making more than double what I had in my first engineering job. The office had great views, they bought us lunch every day, and they let us work from home when we want. This was a job I should be very happy with.</p><p>But there’s only so many years you can try to enjoy working a job that doesn’t challenge you as an engineer and has no real growth potential. So after taking a few years away from engineering to care for family, travel, volunteer, and work on personal projects, I reevaluated doing a BootCamp before returning to software, and I’m so glad I did.</p><p>I have no doubt that I could have learned these skills on the job, or on my own, but the learning speed and motivation that a BootCamp provides are pretty incredible. In four months we covered setting up our machines, data structures, object orientation, HTML, CSS, Javascript, React, JSON, Ruby, Rails, Sinatra, SQLite, PostgreSQL, different full-stack structures, deploying, and more. In addition, through working on projects I worked with various APIs, libraries, and technologies such as Auth0, mui/materials, Next.js, Tailwind CSS, etc.</p><p>Some of this I already knew, some of it I didn’t, but all of it was an incredibly valuable experience. The material was well structured and clear, the instructors were patient and fostered a great learning environment, and my fellow students were lovely and encouraging. I’ve learned plenty of things online on my own through self-guided effort and I have no doubt that what I was able to learn in four months through Flatiron would’ve have otherwise taken me a year or more. Plus, instead of graduating with new friends, it would&#39;ve been a much lonelier path and harder to quantify my experience.</p><p>Everything my cohort has accomplished in the last few months really made me realize how much can be done in a short time if you’re sufficiently motivated and supported. Where could you be in sixteen weeks?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=390f39b94326" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choose Your Friends Carefully, Choose Your APIs and Libraries More Carefully]]></title>
            <link>https://medium.com/@mcdonough.mollya/choose-your-friends-carefully-choose-your-apis-and-libraries-more-carefully-5b260b764e4d?source=rss-f44f1d9da6f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b260b764e4d</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[application]]></category>
            <category><![CDATA[code-library]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Molly McDonough]]></dc:creator>
            <pubDate>Wed, 20 Apr 2022 16:08:03 GMT</pubDate>
            <atom:updated>2022-04-20T17:23:04.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="dog smiling and putting another dog in a headlock with the text “keep your friends close and your frenemies closer”" src="https://cdn-images-1.medium.com/max/474/0*5OY-TrtpKAQnrmsK.jpeg" /></figure><p>As your software projects increase in complexity, chances are you’re going to have to integrate with external APIs and code libraries. A lot of the best libraries and APIs have large teams of experienced engineers working on them for years, and you can utilize all that work on your applications. Choosing the right ones can give you access to verbose data sets needed for your application, and build out a lot of the functionality and styling for you, allowing you to build much more professional, advanced projects in the same amount of time.</p><p>However, many APIs and libraries can be out of date, have many open issues, have unnavigable documentation, etc. So choosing the wrong technologies can, instead of saving you time, increase the complexity, time, and frustration you invest in your project while negatively impacting the number of deliverables you finish. This blog will go over some of the strategies and pitfalls of working with APIs and libraries that I’ve learned the hard way.</p><h3>APIs</h3><p>I highly recommend using <a href="https://rapidapi.com/hub">RapidApi.com</a> to search for APIs. There are other places to find APIs, for example I’ve used GitHub to find lists of free/public APIs, but I’ve had both success and a lot of aggravation testing out random free APIs with little insight into their viability. RapidApi lets you search for APIs, provides lists of top APIs for various categories, and gives you a bunch of information for any API you click on. For example, this API was found by searching for weather APIs and selecting one of the top results:</p><figure><img alt="Screen shot of rapidAPIs about section for Foreca Weather API. Relevant information will be described below." src="https://cdn-images-1.medium.com/max/1024/1*M_PGoTPLXxpad_qozmYlpA.png" /></figure><p>RapidApi shows you the popularity, speed, and service level for Foreca Weather API and gives a link to the product website. Another important tab is the pricing one:</p><figure><img alt="rapidApi’s pricing view for Foreca Weather" src="https://cdn-images-1.medium.com/max/824/1*sy_Q7ozg_iUq_wU4hfq1-g.png" /></figure><p>APIs may have different subscription levels. If they have a free option, it might restrict which endpoints you can access, limit the requests you can make in a month or day, or limit your requests per second. This one has a pretty high request limit of 1000/day but if you need to make requests for the weather in multiple cities at once, the rate limit of 5 requests/second could be prohibitive.</p><p>If the API seems well supported and isn’t cost-prohibitive, next you should look at the APIs documentation, see what endpoints it provides and send test requests to the ones you’ll be utilizing. RapidAPi also lets you see and test requests to the different endpoints:</p><figure><img alt="screen shot of RapidApi’s endpoint view for Foreca Weather API" src="https://cdn-images-1.medium.com/max/1024/1*Isizn_YDHs_0cDeYCOhfXQ.png" /></figure><p>However, going to the product’s website to read about the endpoints and testing with postman or trying to navigate to send get requests from the browser (if there aren’t API keys or other headers required) are also valid approaches.</p><p>To sum up the API vetting process:</p><ol><li>Search for the APIs you need on RapidAPI</li><li>Check their pricing and any request or endpoint limitations</li><li>Read their documentation to make sure you understand what endpoints are offered and how to send requests to them (either on RapidAPI or the product’s website)</li><li>Send test requests to the relevant endpoints.</li></ol><h3>Libraries</h3><p>Code libraries have a similar set of concerns as APIs on a larger scale. A lot more effort goes into building a codebase than an API, so there should be comparably more documentation to read through and more to consider/learn before choosing to work with one on your application. There are various methods of finding code libraries to work with. Search Google, StackOverflow, DeveloperSDK (this tool is meant to be a more verbose tool than RapidApi where you can search for APIs, code libraries, etc. but it doesn’t seem completely built out/useful yet), etc. My preferred method is to search GitHub for libraries. GitHub gives you an idea of the popularity, support, and modernity of a library by how many stars and forks it has, how many open issues it has/how quickly past issues were resolved, and the date of the last update. For a simplistic view of how useful/workable a library is, I tend to search a keyword and a language or framework, for example, “ecommerce react” and sort by the number of stars:</p><figure><img alt="screen shot of searching GitHub for “ecommerce react”" src="https://cdn-images-1.medium.com/max/1024/1*Z2jtGN3xqqOIDhI1CSB2Kw.png" /></figure><p>Before even clicking on the top library, I can already tell it’s probably a great library since 15.7k people starred it, it was updated 6 hours ago, and only 2 issues need help. When I clicked on saleor, I also saw that it has great documentation, with detailed demos and installation instructions. However, it incorporates a lot of different technologies and has some hefty prerequisite installation steps. This is the time to think about your project requirements and timeline. A verbose and sophisticated library like this could save you a phenomenal amount of time if you’re building a secure production e-commerce platform for a medium-sized business and have a few months to get through the installation and usage learning curve with a sophisticated codebase that incorporates some technologies you might not be familiar with. If you only have a few days or weeks to prototype a proof-of-concept application, this library might be too much to delve into.</p><p>For this specific search for an e-commerce React library for a project we only had a few days to work on, we found that the libraries were either too complex to navigate in our timeframe, not well supported/used/documented, or didn’t fit our project constraints. Then we looked for simple react component libraries so we could at least save time on styling buttons, images, etc. We had more luck there, but ended up using the mui/material-ui library we had seen as a dependency for another library we used. This one has 77.8k stars, easy installation, is built only in react, and has incredible documentation where you can copy and paste code snippets for their various components. The takeaway there is that your knowledge of libraries, and tools/sense for searching for new libraries, will grow as you work in a language.</p><p>To sum up the external library vetting process:</p><ol><li>Decide how much time you have to vet external libraries within the timeline of your project.</li><li>Search for libraries by keyword and potentially by language in GitHub. Sort by most stars and review when it was last updated and the number of open issues.</li><li>Check if the library meets your project deliverable requirements, the documentation seems to be good, and the complexity of the library doesn’t exceed your project timeline. Additionally, if there is a paid version of the library, make sure the level you’re willing to pay has the functionality you need.</li><li>If the above requirements are met, take a deeper dive into the documentation. Documentation can be verbose and well-formatted and still be unhelpful. If you think the documentation makes sense, go through the installation steps for the library and try to start getting pieces working.</li><li>The goal in this process is to find a library that suits your project needs, or abandon the library search and build it yourself if there isn’t one that meets your needs, as quickly as possible. As such, don’t be afraid to abandon libraries quickly. A few hours spent reading and installing a library and then deciding it’ll take too much time to get it up and running, or that you can’t customize/utilize the library in the way you need, is far better than spending weeks trying to use a bad library/navigate nonsensical documentation. Be realistic about your time constraints and how much time you want to devote to learning a new library, and which technologies within that library and its dependencies you know/will have to learn.</li></ol><p>Happy coding, dweebs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b260b764e4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Active Record Migrations, Associations, and Aliasing]]></title>
            <link>https://medium.com/@mcdonough.mollya/active-record-tables-794f9a0fd202?source=rss-f44f1d9da6f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/794f9a0fd202</guid>
            <category><![CDATA[aliasing]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[activerecord-association]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[activerecord]]></category>
            <dc:creator><![CDATA[Molly McDonough]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 17:10:25 GMT</pubDate>
            <atom:updated>2022-03-31T18:07:14.081Z</atom:updated>
            <content:encoded><![CDATA[<p>Active record <a href="https://guides.rubyonrails.org/active_record_querying.html#what-is-the-active-record-query-interface-questionmark">performs queries</a> on a connected database for you. It is compatible with most systems, such as MySQL, MariaDB, PostgreSQL, and SQLite.</p><p><a href="https://guides.rubyonrails.org/v3.2/migrations.html">Active record migrations</a> are used to set up and modify your database tables. Migrations, like pretty much everything in ruby, are classes. These are methods on the migration class: add_column, add_index, change_column, change_table, create_table, drop_table, remove_column, remove_index, rename_column.</p><p>This blog will focus on creating your data model. Active record handles typing logic for you. For example, SQLite only supports the data types: integer, real, text and blob. However, active record supports the types: binary, boolean, date, datetime, decimal, float, integer, primary_key, string, text, time, and timestamp. It also supports the special helpers timestamps and references. Timestamps creates created_at and updated_at datetime columns. References creates an integer column that contains the id of the associated record in the referenced table. One nice aspect of Active Record is that when connecting to a SQLite database through Active Record, you don’t have to think about how all those types are being mapped to underlying SQLite types, you only need to interact with the Active Record types.</p><p>Here is an example of using the Active Record migration class to create a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*FiTX66x71ztxSOO5OeWrSA.png" /></figure><p>This code will create a table called “auditions” with the following columns:</p><ul><li>actor: accepts data type string, with a limit of 50 characters that cannot be null</li><li>location: accepts a string. Can be null or of any length</li><li>phone: integer</li><li>hired: boolean, defaults to false</li><li>role_id: integer, points to the role table. Could have also been written as “t.references :role”</li><li>t.timestamps creates the following columns: &lt;t.datetime “created_at”, null: false&gt; and &lt;t.datetime “updated_at”, null: false&gt;</li></ul><p>This association between the roles and auditions table will be paired with Role and Audition classes that inherit from ActiveRecord::Base. <a href="https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/create_table">Here</a> is some additional information/notations for table creation.</p><p>Here is an example of those classes with methods built to update the hired status of an audition for a particular role, and to record those hired first and second as the lead and understudy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*hy-bUegCOQHIQFxvWAhQGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*XuNAkN9tEjFiml2rnHdKgw.png" /></figure><p>In this situation, where you wish to reference a table more than once, or if you in general wish to call a reference column by some other name, you can also use <a href="https://guides.rubyonrails.org/active_record_basics.html#migrations">aliasing</a>. Active Record associates tables by adhering to expected naming conventions with the table name being the pluralized version of the active record base class name. The reference columns named as the class(singular)_id (i.e. role_id to reference a table called “roles” populated by a class “Role”). And association macros in the classes such as has_many :auditions and belongs_to :role. This is great when for not having to write out all the underlying association logic. However, additional steps must be taken if you want to diverge from those naming conventions in both the table migraations and the active record base class associations.</p><p>Here is the above example done with aliasing:</p><p>These migrations (see how I reference tables that don’t exist in the CreateRoles migration):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*xXDZbHaqI-1DUL5eKWnK5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*iKoxzQJkXRTjZW2sjcTOHg.png" /></figure><p>Create the following db schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*YlFSb1b8XDltNDeBOj5B9g.png" /></figure><p>The Audition class associates to the role class in the same way, since it is not the one aliasing. However, through that association, it now has access to audition_instance.role.lead_id and audition_instance.role.understudy_id fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*wb9uN4H-vAOzYdlljeIKnQ.png" /></figure><p>Here is where the aliasing is handled. Role belongs to the references “lead” and “understudy” which were defined in the migration (this naming matches up as active record expects), but we have the additional detail of the class_name those references belong to. This is how Role knows those references will be Auditions rather than the non-existent classes Lead and Understudy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*y77Uju-cMlrfARN9w6uVTQ.png" /></figure><p>Aliasing works slightly differently when you want to alias a has_many relationship. This makes sense since the aliased table won’t be listed in the migration since the reference id is on the belongs_to table.</p><p>For example, if we wanted to model out a system of users reviewing and favoriting games. A user has many reviews, and has many favorites. A user then has many games through reviews, and has many games through favorites. (I’m not going into explaining “through” associations, but you can read about them <a href="https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association">here</a> if you’re unfamiliar with the concept.) This means a user can leave reviews for many games, and save many games as favorites. However, we wouldn’t want a game a user left a review of “1 star: most boring game I’ve ever played. Lessened my will to live by 12%” among that user’s favorites! So how do we differentiate in the User class between associated favorite games, and associated reviewed games? With aliasing! For aliasing a has_many relationship, you define both how the aliased class will be called, and the actual name of the class like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*ID7haqi-s2Gaf7cJx9h2OA.png" /></figure><p>And no renaming is needed on the belongs to table you’re going through:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*oUG5qLl9wtbxMoRMP_qL3Q.png" /></figure><p>On the other end, a game also has many users through reviews, and has many users through favorites. For this example, a game also has many categories, and a category has many games, through the join table game_categories. That’s not relevant to aliasing, but does show the naming convention of join tables which is “first table singular_second table plural” i.e. game_categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*IAoajWJiIG8m0rpEyp-8fQ.png" /></figure><p>Anyway. That’s all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794f9a0fd202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useState React Hook]]></title>
            <link>https://medium.com/@mcdonough.mollya/usestate-react-hook-3375919b70f6?source=rss-f44f1d9da6f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3375919b70f6</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Molly McDonough]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 23:40:51 GMT</pubDate>
            <atom:updated>2022-03-08T23:40:51.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A series of images with labels for: picture hooks, coat hook, fish hook, curtain hooks, react hooks (with a developer facedown on his laptop), and left hook (with a boxer punching a bag)." src="https://cdn-images-1.medium.com/max/1024/1*BEpOkZafxCutFlpoOQ-lRw.png" /></figure><p>According to the <a href="https://reactjs.org/docs/hooks-intro.html">React hooks documentation</a>, hooks were added in React version 16.8 and let you hook into React functionality without writing a class. This blog will focus on how and when to use a popular React hook- useState (which is briefly explained in the above documentation along with rules of using hooks).</p><p>useState is a hook that allows you to, as the name suggests, use the React state functionality. Whenever a state variable is updated, any component dependent on that variable will rerender with the new value. This takes care of keeping your components dynamic based on updating variables. The usage of useState is as follows:</p><pre>import React, {useState} from &#39;react&#39;;</pre><pre>function App() {<br>    const [stateVariable, setStateFunction] = useState(&quot;initial value&quot;);</pre><pre>  return (<br>    &lt;main&gt;<br>        {stateVariable}<br>    &lt;/main&gt;<br>  );<br>}</pre><pre>//useState can be used to maintain the state of any javascript variable type. Here are some common initilizations you might see.</pre><pre>const [stateBoolean, setStateBoolean] = useState(false);<br>const [stateString, setStateString] = useState(&quot;&quot;);<br>const [stateCounter, setStateCounter] = useState(0);<br>const [stateArray, setStateArray] = useState([]);</pre><p>It is best to update the state variable by calling the setStateFunction (the second argument returned by calling useState), rather than updating the state variable directly.</p><pre>//From the above example:<br>setStateCounter(stateCounter + 1);<br>setStateCounter(1);</pre><pre>//Both automatically set stateCounter=1 and automatically rerender any component that has stateCounter as a parameter. Though on the first is actually going to function as a counter, both are preferable to the following:<br>stateCounter=1;</pre><pre>//And in my example this is not an option because I initialized the counter and function as const. </pre><p>Even when working with state arrays and objects, where you could modify a property on the array or object, you shouldn’t do so directly. For useState to cause a rerender, it needs to recognize that the state variable has changed, and updating an array destructively will not make that array point to a new location in memory, and thus according to state, it is the same. Common methods for saving a new array with changes from the previous state array include Array.map(), Array.filter(), and the spread operator.</p><p>When used in conjunction with passing callback functions as props, state also enables an event on a child component to update a piece of state that will reflect in parent and even sibling components. You can pass the state update function directly as a prop to a child component with the state variable:</p><figure><img alt="A simple example of the parent component passing a state variable and state function to a child component as props." src="https://cdn-images-1.medium.com/max/1024/1*sTuwXR2mSHmI4CErxsSSYQ.png" /></figure><figure><img alt="Child component that updates the state based on a button click" src="https://cdn-images-1.medium.com/max/1024/1*sIxKEd9P7Q6Ws83f4bpMNw.png" /></figure><figure><img alt="screen grab of the parent and child rendered in the browser before a click. The parent says “Click Child” and the child button says “click me!”" src="https://cdn-images-1.medium.com/max/179/1*AoEyN6N0yHXRNOzAKmF3jQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*aJsTe5jHpAM8l1Pmgg-M2A.png" /></figure><p>Or you can pass a handler function down from the parent component that will do some data manipulation and then call the state update function. Since state updates are called asynchronously, the updated state variable value won’t be available within the handler function. It will be available in the rerendered components.</p><figure><img alt="screen grab of a simple react counter component illustrating that the updated value of the state variable isn’t available inside a helper function. It is available when the components are rerendered." src="https://cdn-images-1.medium.com/max/1024/1*0SyFYC8slmO7C5_fPuGP0g.png" /></figure><p>Here is an example of using handler functions, as well as updating siblings based on state, as well as what happens when we update a variable that isn’t being maintained in state. Only showing one child button since they’re essentially the same (so probably we wouldn’t actually create two separate components for this beyond an example of sibling state).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQgxwvAfmBzKrrN2YEgqXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcJCplA2fM_FszQJdn-OUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*ysaFaIl2V70mkUTLKVMlcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*Jb9GTcqqIxSF5BXobMDfJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*u1ip6dx6PDu6PBK-Z8MTPw.png" /></figure><p>You can see that the siblings are updating based on the state of their button, and the state of the other button both maintained in the parent and passed as props. However, the parent header text isn’t updating even though we update it in the same helper state function where we update the buttons’ state. That is because headerText isn’t a state variable, so react doesn’t know to rerender the Parent component with this updated value. So we could either do some ternary logic to choose the header text based on the buttons’ state like we did for the button text, or maintain a separate peace of state for the headerText.</p><p>You can read about React state in more detail in the <a href="https://beta.reactjs.org/learn/managing-state">beta documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3375919b70f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Nested Objects in JavaScript]]></title>
            <link>https://medium.com/@mcdonough.mollya/working-with-nested-objects-in-javascript-aad41ae5ed85?source=rss-f44f1d9da6f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/aad41ae5ed85</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Molly McDonough]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 18:45:50 GMT</pubDate>
            <atom:updated>2022-03-04T22:30:04.734Z</atom:updated>
            <content:encoded><![CDATA[<p>Objects are JavaScript’s only non-primitive <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">data type</a>. They store key, value pairs. Keys are always strings, and the values can be any data type (numbers, booleans, other objects, etc.). The syntax for the initialization of an object is as follows:</p><pre>const obj = {keyOne: &quot;valueOne&quot;, keyTwo: &quot;valueTwo&quot;, keyThree: &quot;valueThree&quot;};</pre><p>Because JavaScript requires object keys to be strings, I do not need quotes around the keys. However, since values can be any data type, for JavaScript to know my values are strings, they must be enclosed in quotes. If the values weren’t in quotes, they would need to be a different data type, or JavaScript will expect a variable.</p><p>For example, the following object is fine:</p><pre>const obj = {keyOne: 1, keyTwo: false , keyThree: null};</pre><p>But this object will throw an error:</p><pre>const obj = {keyOne: valueOne};</pre><pre>//console<br>ReferenceError: valueOne is not defined<br>    at Object.&lt;anonymous&gt; (/home/runner/Nested-Object/index.js:1:22)<br>    at Module._compile (node:internal/modules/cjs/loader:1101:14)</pre><p>This indicates that we can also initialize objects by variables. We can do this in our initial declaration, or with dot or bracket notation:</p><pre>const valueOne = &quot;Shh I&#39;m a variable&quot;;</pre><pre>const obj = {keyOne: valueOne};</pre><pre>obj.keyTwo = 2;</pre><pre>//bracket notation doesn&#39;t require a literal string like dot notation, so if I want my key to be the string &quot;keyThree&quot; rather than whatever is stored in a variable named keyThree, I need quotes</pre><pre>obj[&quot;keyThree&quot;] = &quot;Three&quot;;</pre><pre>const keyFour = &quot;Variable used to set a key with bracket notation on the next line&quot;;<br>obj[keyFour] = 4;</pre><pre>console.log(obj);</pre><pre>//console<br>{<br>  keyOne: &quot;Shh I&#39;m a variable&quot;,<br>  keyTwo: 2,<br>  keyThree: &#39;Three&#39;,<br>  &#39;Variable used to set a key with bracket notation on the next     line&#39;: 4<br>}</pre><p>Properties can also be accessed by dot notation if you know the literal string. Bracket notation must be used for any keys with characters not accepted by dot notation (such as my spaces in the above example), or if you are passing the value of a variable rather than the literal string.</p><p>Now that I’ve covered the basic syntax of JavaScript objects I want to talk about nested objects. Because the values of JavaScript objects can be any data type, we can have nested objects such as the following:</p><pre>const customers = {<br>  Molly: {<br>    email: &quot;address@gmail.com&quot;,<br>    age: 31,<br>    householdMembers: [&#39;mom&#39;, &#39;dad&#39;, &#39;brother&#39;, &#39;cat&#39;],<br>    address: {<br>       street: &quot;123 Street Ave&quot;,<br>       street2: &quot;apt 1&quot;,<br>       city: &quot;Ithaca&quot;,<br>       state: &quot;New York&quot;<br>    }<br>  },<br>  Ahmad: {<br>    email: &quot;address2@hotmail.com&quot;,<br>    age: 30,<br>    address: {<br>      street: &quot;321 Avenue Way&quot;,<br>      city: &quot;San Diego&quot;,<br>      state: &quot;California&quot;<br>    }<br>  }<br>}</pre><pre>//Note that the quotes around 3 are optional because of the way JavaScripts treats array indexes as strings<br>console.log(customers[&quot;Molly&quot;][&quot;householdMembers&quot;][&quot;3&quot;])<br>//cat</pre><pre>console.log(customers.Ahmad.address.state)<br>//California</pre><p>That’s all fine and good when you definitely know what your key path is/that all your data is structured exactly the same way. However, what if we aren’t sure if we have a customer named Hannah, but if we do, we want to grab her email?</p><pre>//console<br>customers.Hannah.email<br>customers[&quot;Hannah&quot;][&quot;email&quot;]</pre><pre>//either of the above lines results in the following error:<br>TypeError: Cannot read properties of undefined (reading &#39;email&#39;)<br>    at REPL14:1:18<br>    at Script.runInContext (node:vm:139:12)<br>    at REPLServer.defaultEval (node:repl:564:29)<br>    at bound (node:domain:421:15)<br>    at REPLServer.runBound [as eval] (node:domain:432:12)<br>    at REPLServer.onLine (node:repl:889:10)<br>    at REPLServer.emit (node:events:390:28)<br>    at REPLServer.emit (node:domain:475:12)<br>    at REPLServer.Interface._onLine (node:readline:487:10)</pre><p>We’re trying to access the email property on undefied and erroring out our code. To solve this, we can use conditionals and only proceed to more deeply nested object properties if each previous level exists, or we can use Oliver Steele’s nested object access pattern. For our example this looks like:</p><pre>(customers.Hannah || {}).email<br>//console<br>undefined</pre><p>This says if the first value exists, get the email property for it. If not check the email property on the empty object. It returns an undefined rather than erroring out.</p><p>What if we want to access a more deeply nested property we’re not sure exists though? It’ll be kind of annoying to do this on every level:</p><pre>console.log(((customers.Molly || {}).address || {}).street2);<br>//apt 1</pre><p>This isn’t even that deeply nested of an object and it’s already getting confusing to follow. When we want to check if each level of our key path exists, we can also use the array reduce method with an array of keys.</p><pre>const customers = {<br>  Molly: {<br>    email: &quot;address@gmail.com&quot;,<br>    age: 31,<br>    householdMembers: [&#39;mom&#39;, &#39;dad&#39;, &#39;brother&#39;, &#39;cat&#39;],<br>    address: {<br>       street: &quot;123 Street Ave&quot;,<br>       street2: &quot;apt 1&quot;,<br>       city: &quot;Ithaca&quot;,<br>       state: &quot;New York&quot;<br>    }<br>  },<br>  Ahmad: {<br>    email: &quot;address2@hotmail.com&quot;,<br>    age: 30,<br>    address: {<br>      street: &quot;321 Avenue Way&quot;,<br>      city: &quot;San Diego&quot;,<br>      state: &quot;California&quot;<br>    }<br>  }<br>}</pre><pre>//return the apartment number for a customer if it exists<br>function getApt (customerName) {<br>  const path = [customerName, &quot;address&quot;, &quot;street2&quot;];<br>  const apt = path.reduce((object, key) =&gt; {<br>    return (object || {})[key];<br>    }, customers);<br>    <br>    return apt;<br>}</pre><pre>//calling the function will return the following in the console:<br>getApt(&quot;Molly&quot;)<br>//apt 1<br>getApt(&quot;Ahmad&quot;)<br>//undefined<br>getApt(&quot;Hannah&quot;)<br>//undefined</pre><p>Here’s a helpful <a href="https://betterprogramming.pub/4-ways-to-safely-access-nested-objects-in-vanilla-javascript-8671d09348a8">blog</a> with additional examples/explanation on accessing nested objects.</p><p>I’m a beginner with JavaScript so this is a beginners guide. If you’re not too overwhelmed by a bunch of programming terms at this stage, you can read the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">MDN documentation</a> on objects, or their guide on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects">working with objects</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aad41ae5ed85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>