<?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 Daniel Calvin on Medium]]></title>
        <description><![CDATA[Stories by Daniel Calvin on Medium]]></description>
        <link>https://medium.com/@Arockne?source=rss-322a735e6272------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GCwYynNSF0uFHPK9wtZeTw.jpeg</url>
            <title>Stories by Daniel Calvin on Medium</title>
            <link>https://medium.com/@Arockne?source=rss-322a735e6272------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:37:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Arockne/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[Cloud Adoption and Emerging Technologies]]></title>
            <link>https://medium.com/@Arockne/cloud-adoption-and-emerging-technologies-69e8b1f1573d?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/69e8b1f1573d</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-benefit]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-adoption]]></category>
            <category><![CDATA[emerging-technology]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 00:49:32 GMT</pubDate>
            <atom:updated>2022-10-09T00:49:32.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZO6jyHyfPhMUNr_HgLOLYw.png" /><figcaption>Image by <a href="https://pixabay.com/users/tumisu-148124/">Timusu</a> from <a href="https://pixabay.com/">Pixabay</a></figcaption></figure><p><a href="https://www.flexera.com/blog/cloud/cloud-computing-trends-2022-state-of-the-cloud-report/">The number of enterprises using the cloud continues to accelerate</a>; it is no longer a choice of <strong>if</strong> a business should adopt the cloud but <strong>what</strong> is their cloud adoption strategy. When working with the cloud, enterprises have solved many challenges, such as providing better customer service, removing barriers to innovation, achieving better scaling, and accelerating growth. In addition, with the development of the cloud came about some technologies that are being accelerated by the cloud, such as the internet of things(IoT), artificial intelligence(AI), blockchain, and analytics.</p><h3>Considerations when working on a cloud adoption strategy</h3><ol><li>Infrastructure and workloads</li></ol><p>Does the cost of building and operating a data center outweigh the benefit of the low initial value and possible cost savings with the pay-as-you-go model with the cloud?</p><p>2. SaaS and development platforms</p><p>Would it be better to use software off-the-shelf and invest in upgrades or use the software on the cloud?</p><p>3. Speed and productivity</p><p>What would it mean for an organization to get an application up and running in a matter of hours, then weeks or months? How about a decrease in labor costs when using cloud analytics tools?</p><p>4. Risk Exposure</p><p>What is the impact on the organization of making the wrong decision? Would it be better to buy hardware and software or pay-as-you-go? Would it be beneficial to trial before making any long-term decisions?</p><h4>Benefits of cloud adoption</h4><ol><li>Flexibility</li><li>Efficiency</li><li>Strategic Value</li></ol><p>The flexibility of the cloud allows users to access the cloud anywhere with an internet connection and scale and customize their cloud services to fit their needs. In addition, users can use the efficiency of the cloud to get applications to market quickly while saving on infrastructure costs and maintenance by paying on a per-use basis through the cloud provider. However, organizations must keep up with the most innovative technologies, which can be time-consuming and costly. With the cloud, enterprises always use the most innovative technologies while managing the underlying infrastructure. As a result, cloud-based technology allows organizations to focus more on their objectives.</p><h4>Challenges of cloud adoption</h4><ul><li>Data security, associated with loss or unavailability of data causing business disruption</li><li>Governance and sovereignty issues</li><li>Legal, regulatory, and compliance issues</li><li>Lack of standardization in how the constantly evolving technologies integrate and interoperate</li><li>Choosing the correct deployment and service models to serve specific needs</li><li>Partnering with the right cloud service providers</li><li>Concerns related to business continuity and disaster recovery</li></ul><h3>Technologies being accelerated by the cloud</h3><ol><li>Internet of things(IoT)</li><li>Artificial Intelligence(AI)</li><li>Blockchain</li><li>Analytics</li></ol><p><em>IoT</em> is a network of physical objects connected to the internet, like smart devices. These devices generate vast amounts of data, and the data generated is stored and processed on the cloud. Therefore, cloud computing supports and enables IoT because of the amount of data generated.</p><p><em>AI</em> is a system that perceives its environment and takes actions that maximize its chance of achieving its goals. AI learns from data generated from IoT devices to generate insights while storing and processing the data on the cloud.</p><p><em>Blockchain</em> is a secure, immutable network that allows members to view only the transactions relevant to them. This technology provides a trusted decentralized source of truth. Blockchain provides the data from the source, AI powers the analytics and decision-making, and the cloud supports the resources for storage and processing power to generate insights from this data.</p><p><em>Analytics</em> is leveraging flexibility, scalability, and computing resources on the cloud. Analytics uses the power of the cloud to track trends to predict future events, build machine learning models, and drive new value.</p><h3>Summary</h3><p>When adopting the cloud, businesses must build a strategy that would best support their business and customers without causing business disruptions and security, compliance, and performance issues. In addition, the cloud supports technologies such as the internet of things(IoT), artificial intelligence(AI), blockchain, and analytics. These technologies allow businesses to grow, innovate, and create customer value.</p><ul><li><a href="https://www.flexera.com/blog/cloud/cloud-computing-trends-2022-state-of-the-cloud-report/">Trends in Cloud Computing: 2022 State of the Cloud Report | Flexera Blog</a></li><li><a href="https://www.edx.org/course/introduction-to-cloud-computing-6?index=product_value_experiment_a&amp;queryID=884cc2099928aa6ab3ca3e9e0994efc4&amp;position=1">Introduction to Cloud Computing</a></li><li><a href="https://www.netapp.com/cloud-services/what-is-cloud-analytics/">What Is Cloud Analytics? | NetApp</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e8b1f1573d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Computing Overview]]></title>
            <link>https://medium.com/@Arockne/cloud-computing-overview-eb80d1f5ec01?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb80d1f5ec01</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 01:48:52 GMT</pubDate>
            <atom:updated>2022-10-05T01:48:52.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFsOaWAZLLulhR7H1pJxjQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/akitada31-172067/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=6515064">Roman</a> from <a href="https://pixabay.com/">Pixabay</a></figcaption></figure><h3>What is Cloud Computing?</h3><blockquote>Cloud computing is a model for enabling ubiquitous, convenient, on-demand network access to a shared pool of configurable computing resources that can be rapidly provisioned and released with minimal management effort or service provider interaction. — <a href="https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-145.pdf">US National Institute of standards and technology (NIST)</a></blockquote><p>Cloud computing enables us to allocate and configure resources such as networks, servers, storage, applications, and services. These resources are dynamically assigned and scaled in response to the user’s needs. Without the development of virtualization and hypervisor, cloud computing would not be as it is today. These technologies allowed us to take a <a href="https://en.wikipedia.org/wiki/Node_%28networking%29">physical node</a> and split it into multiple <a href="https://www.vmware.com/topics/glossary/content/virtual-machine.html">virtual machines</a> while configuring each device to be allocated a specific amount of resources. In addition, since the hardware is expensive, cloud technologies allowed certain companies to make the cloud’s benefits more accessible and make services available with a pay-as-you-go model, which was the catalyst to the growth of cloud computing.</p><h3>Brief history and evolution of cloud computing</h3><p>In the 1950s, large-scale mainframes with high-volume processing power were being developed with <a href="https://en.wikipedia.org/wiki/Time-sharing">time-sharing</a>, which evolved to allow multiple users to access the same data storage layer and CPU power. In the 1970s, mainframes were now able to host multiple virtual machines on a single physical node. As a result, the development of virtualization helped companies lower the cost of hardware. Also, it allowed servers to be virtualized to shared hosting environments, private servers, and virtual dedicated servers.</p><p>If a company needed a specific number of machines, it could split one physical node into multiple virtual systems enabled by hypervisors. A <em>hypervisor</em> is a small software layer that allows multiple operating systems to run alongside each other, sharing a pool of resources. Each virtual machine is separated logically and assigned its resources, preventing other devices from interfering with each other. So, for example, the other devices would be unaffected if something were to go wrong on one virtual machine, like a security compromise or crash.</p><p>Once technology and hypervisors improved, some companies decided to make the cloud’s benefits more accessible with a pay-as-you-go model. Using this model, a user would order a specific amount of resources from one of these companies. Once the cloud has become more popular, these companies would now have a pay-per-use model. This model allowed users to pay for resources when needed, scale up during peaks, and scale down when there was low usage. As a result, the Pay-per-use model was more cost-effective and gave rise to modern cloud computing.</p><h3>Essential characteristics of cloud computing</h3><ol><li>on-demand self-service</li><li>broad network access</li><li>resource pooling</li><li>rapid elasticity</li><li>measured service</li></ol><p><strong>On-demand self-service</strong> allows access to cloud resources the consumer needs without human interaction.</p><p><strong>Broad network access </strong>allows<strong> </strong>access to cloud resources through standard mechanisms and platforms such as mobile phones, tablets, laptops, and workstations.</p><p><strong>Resource pooling </strong>allows consumers access to a pool of computing resources such as storage, processing, memory, and network bandwidth to serve multiple consumers using a <a href="https://en.wikipedia.org/wiki/Multitenancy">multi-tenant</a> model. Resources are dynamically assigned and reassigned according to consumer demand.</p><p><strong>Rapid elasticity</strong> allows the consumer to access as many resources as needed and scale back when needed.</p><p><strong>Measured service</strong> allows the consumer to leverage the cloud’s metering capability and only pay for use.</p><h3>Cloud computing providers and services</h3><p>There are many cloud providers, such as Amazon Web Services(AWS), Google Cloud Platform(GCP), IBM cloud, Microsoft Azure, Oracle Cloud, Salesforce, and SAP. Each provider host variety of services such as software-as-a-service(SaaS), platform-as-a-service(PaaS), and infrastructure-as-a-service(IaaS).</p><p><strong>IaaS</strong> allows the consumer access to infrastructure and physical computing resources without needing to manage or operate them.</p><p><strong>PaaS</strong> provides the consumer the platform to create an application using the programming languages, libraries, services, and tools available through the provider.</p><p><strong>SaaS</strong> provides consumer applications running on the cloud and licensed on a subscription basis.</p><h3>Summary</h3><p>Cloud computing is the delivery of on-demand computing resources over the internet on a pay-as-you-go basis. Resources are scaled, assigned, and reassigned in response to users’ needs per-use basis. Modern-day cloud computing would not be as it is today without the development of virtualization technologies and hypervisors — cloud providers host infrastructure, platforms, and software as a service. As a result, cloud computing will continue to grow, and if an organization has not thought about how to incorporate the cloud to serve the business and customers best, it may be left behind.</p><ul><li><a href="https://csrc.nist.gov/publications/detail/sp/800-145/final">NIST Special Publication (SP) 800-145, The NIST Definition of Cloud Computing</a></li><li><a href="https://en.wikipedia.org/wiki/Node_(networking)">Node (networking) - Wikipedia</a></li><li><a href="https://www.vmware.com/topics/glossary/content/virtual-machine.html">What is a Virtual Machine? | VMware Glossary</a></li><li><a href="https://www.edx.org/course/introduction-to-cloud-computing-6?index=product_value_experiment_a&amp;queryID=884cc2099928aa6ab3ca3e9e0994efc4&amp;position=1">Introduction to Cloud Computing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb80d1f5ec01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Overview of Data Engineering]]></title>
            <link>https://medium.com/@Arockne/brief-overview-of-data-engineering-9baf1387ec88?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/9baf1387ec88</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Thu, 29 Sep 2022 19:13:58 GMT</pubDate>
            <atom:updated>2022-09-29T19:13:58.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TnibgNQeydwK-1yZe6w_fQ.jpeg" /><figcaption>Photo By <a href="https://www.pexels.com/photo/colleagues-looking-at-survey-sheet-3183153/">fauxels</a> from <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><h3>What is data engineering?</h3><p>Data Engineering is the discipline of developing and maintaining data architectures and processing data to become analysis-ready for business operations and analysts. Data engineers collect, process, and store data in data repositories. Data engineers ensure that data is highly available, consistent, secure, and recoverable. Data engineers also design and manage pipelines that encompass the data journey from source to destination systems. The world of data consists of many different roles with crucial differences that are vital to the data ecosystem.</p><h3>Differences between data engineering and other data roles</h3><p>A few of the many roles in data are:</p><ul><li>Data Engineers</li><li>Data Scientists</li><li>Data Analytics</li><li>Business Analysts</li><li>Business Intelligence Analyst</li></ul><p>The significant difference in these roles is in how they use data:</p><ol><li>Data engineers convert raw data from disparate sources into usable data.</li><li>Data analysts use analysis-ready data to generate insights.</li><li>Data scientists predict the future by using data from the past.</li><li>Business and intelligence analysts use the insights generated to make decisions that would benefit and grow their business.</li></ol><h3>An example of a day in the life of a data engineer</h3><p>A team of data scientists will create a dashboard prototype using <a href="https://en.wikipedia.org/wiki/Sentiment_analysis">sentiment analysis</a> to keep an eye out for what everyone is saying about the business product. Once the business team gives the thumbs up on the prototype, the group of data engineers will make this prototype a reality. The data engineers will start with extracting data needed from disparate sources for temporary storage. These disparate sources can include data from APIs and data from web scraping.</p><p>Once the data is in temporary storage, the data engineers will inspect the data to assess any transformations needed to be conducted on the data. Once reviewed, the data engineers will create a program to process the data and load it into a database. Then from the database, the data will be pulled by the dashboard and displayed in reports. If the results of these steps meet the business requirements, then the data engineers would need to automate the process by building a data pipeline by extracting, loading, and transforming the data into the database on an ongoing basis.</p><h3>Different entities that form a modern data ecosystem</h3><p>The modern data ecosystem includes a network of interconnected and continually evolving entities, including:</p><ul><li>Data</li><li>Enterprise Data Environment</li><li>End-Users</li></ul><p>Data is available in various formats, structures, and sources. The data formats can be a relational or non-relational database, APIs, Web services, data streams, social platforms, and sensor devices. The different types of data structures are typically classified as structured, semi-structured, or unstructured. The data sources can come from text, images, video, IoT devices, real-time data, legacy databases, etc.</p><p>An Enterprise data environment is where the raw data is staged for processing to be organized, clean, and optimized for use by end-users.</p><p>End-Users are roles such as analysts, programmers, business stakeholders, and other technical roles.</p><h3>Tasks performed in a typical data engineering lifecycle:</h3><ul><li>Gathering Data from disparate sources</li><li>Integrating data into a unified view for end-users</li><li>Preparing data for analytics and reporting by transforming and cleansing the data</li><li>Design and manage data pipelines for continuous flow of data from source to destination systems</li><li>Managing the complete data infrastructure for the collection, processing, and storage of data</li></ul><h3>Summary</h3><p>The main goal of a data engineer is to make quality data available for fact-finding and data-driven decision-making. Data engineers extract, integrate, and organize data from disparate sources and store data in data repositories. Data engineers ensure that stored data is consistent, accurate, reliable, secure, and recoverable for end-users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9baf1387ec88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React: Mocking with MSW, React Testing Library, and Jest with Redux]]></title>
            <link>https://medium.com/@Arockne/react-mocking-with-msw-react-testing-library-and-jest-with-redux-faa02ffc3abf?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/faa02ffc3abf</guid>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[msw]]></category>
            <category><![CDATA[react-testing]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 12:58:05 GMT</pubDate>
            <atom:updated>2022-06-24T12:58:05.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*nMPHhv65i-kpM0Fmj2fdAQ.jpeg" /></figure><h3>What is mocking?</h3><blockquote>Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects with mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.</blockquote><blockquote>In short, mocking is creating objects that simulate the behavior of real objects.</blockquote><p>The benefit of mocking is that it allows you to be confident that your test will get the expected result every time. Testing with real-world objects has a chance of failing over time. Mocking is especially useful when testing an external API. This becomes especially useful when testing with a payment API. Mocking out the payment API allows you to test features without relying on having a real-world balance.</p><h3>Before we begin</h3><p>We will be implementing the use of mocking and testing within the application I made. If you would like to code along, go ahead and fork from the msw-blog branch. We will be mocking out our requests to the backend API. Once the repository is forked and cloned, go ahead and run some commands.</p><pre>#The application assumes that bundler, npm, ruby, rails, and postgresql is installed</pre><pre><strong>Run these commands</strong>:<br>bundle install<br>rails db:create db:migrate db:seed<br>npm install --prefix client</pre><h4>MSW setup</h4><p>Run this command in the client directory:</p><pre>npm install msw --save-dev</pre><h3>Mocking out API calls</h3><p>To get started, head-on into the <strong>/client/src</strong> directory. Once we are in the correct directory you will find a <strong>__mocks__</strong> directory. This directory is where all our mocks will live and <a href="https://jestjs.io/docs/manual-mocks">Jest</a> will load these mocks for us automatically. We will be mocking out the resources for characters. Let’s create <strong><em>character.js</em></strong> file within our ___mocks__ directory. Within the character file is where we will be implementing our handlers to manage our API mocks using <a href="https://mswjs.io/">MSW</a>.</p><h4>Getting started with MSW</h4><p>Let’s add the initial import for MSW</p><pre>import { rest } from &#39;msw&#39;</pre><p>The <strong>rest</strong> API contains methods that allow us to mock out our RESTful API. Each method accepts two arguments:</p><ol><li>RESTful route</li><li>response resolver</li></ol><p>The <strong>response resolver</strong> is a function we will be using to return our response to our test. The response resolver takes three arguments:</p><ol><li><strong>req</strong>- Stores information about the request to the API</li><li><strong>res</strong>- Function to create a mocked response</li><li><strong>ctx</strong>- Set of methods that set several things that would be included in a response like body, headers, status code, etc…</li></ol><p>Let’s implement our handlers. The handlers are going to be an array of our mocked requests. The handlers are what we will import into our test files in the future.</p><pre>export const characterHandlers = []</pre><p>Add this mock data to the top of the character file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf5d180f2b4ec046f91de090364e88ec/href">https://medium.com/media/cf5d180f2b4ec046f91de090364e88ec/href</a></iframe><h4>Creating our handlers for our mock requests</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd0ddedb7c5ab6235416f3d5785b3a0a/href">https://medium.com/media/bd0ddedb7c5ab6235416f3d5785b3a0a/href</a></iframe><p>After creating our handlers with our mock data. We are now able to imitate our requests to the backend API. We will now configure the server for our mocked requests.</p><h4>Setting up a server with MSW</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f56da069460d319e7c80de01e91e427/href">https://medium.com/media/4f56da069460d319e7c80de01e91e427/href</a></iframe><p>For every test file that needs mocking of an API, this functionality will need to be added before any tests.</p><h3>Testing user behavior with character mocks</h3><p>First, we will need to create a <strong>__tests__</strong> directory within the <strong>src/features/character</strong> directory. Our tests should be as close as possible to the file we are testing. After creating our directory, let’s test out our mock for our get request to our index route by testing out the CharactersContainer. We will name the test file the same name as the file we are testing from. Let’s create CharactersContainer.js file in the __tests__ directory. Once we have our file let’s add the server setup from earlier.</p><p>Currently, I am abstracting away the react testing library render method with wrapper components. We will need to add the characterSlice to the store within <strong>src/utils/test-utils.js, </strong>since I am using redux.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3821ed1b244df752d049f3de7981bbc/href">https://medium.com/media/f3821ed1b244df752d049f3de7981bbc/href</a></iframe><h4>Test getting characters with the index route</h4><p>After our initial setup, let’s start by creating our first test. We will start by rendering the CharactersContainer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64138b6cf9b2d6ff0c805c66ec93b199/href">https://medium.com/media/64138b6cf9b2d6ff0c805c66ec93b199/href</a></iframe><p>Side Note: The test was running an error with ResizeObserver because of the component library I am using. The solution to that error was to monkey patch ResizeObserver.</p><p>Now that we have rendered our CharactersContainer component, we will need to test to see if our characters are rendered to the screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e014fec32e83b38c4603f5faba16b97d/href">https://medium.com/media/e014fec32e83b38c4603f5faba16b97d/href</a></iframe><p>Now that we have a passing test we can move on to the other mocks.</p><h4>Test getting a character then deleting the character</h4><p>We will be writing this test in the <strong>client/__tests__/App.js</strong>. We will also need to add the characterHandlers to our server setup at the beginning of the file.</p><pre>const server = setupServer(<br>...handlers,<br>...characterHandlers,<br>...campaignHandlers<br>)</pre><p>The resize error will pop up here as well so we will need to monkey patch once again. Add this to the top of the file below the imports.</p><pre>class ResizeObserver {<br>  observe() {}<br>  unobserve() {}<br>}</pre><p>Now let’s write out the steps the user would take to delete a character from home.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4dfd57a35a098c2d63395dba124d2c8/href">https://medium.com/media/a4dfd57a35a098c2d63395dba124d2c8/href</a></iframe><p>With each of these tests, we can observe our mocks within the components we are testing. If we were to place a debugger or console.log, we can see our mocks with the mock data in action.</p><h4>Summary</h4><p>MSW allows you to implement mocking of server requests. MSW is especially useful when you need to mock out an external API like a payment API. Overall MSW is awesome. Thank you for reading.</p><p>Resources:</p><ul><li><a href="https://mswjs.io/">Mock Service Worker</a></li><li><a href="https://testing-library.com/">Testing Library | Testing Library</a></li><li><a href="https://jestjs.io/">Jest</a></li><li><a href="https://github.com/Arockne/dnd5e-companion/tree/msw-blog">GitHub - Arockne/dnd5e-companion at msw-blog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faa02ffc3abf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live Chat Implemented with Action Cable in a React/Rails Application]]></title>
            <link>https://medium.com/@Arockne/live-chat-implemented-with-action-cable-in-a-react-rails-application-95b261a4d203?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/95b261a4d203</guid>
            <category><![CDATA[actioncable]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Sun, 27 Feb 2022 14:39:30 GMT</pubDate>
            <atom:updated>2022-08-11T21:05:27.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*4pgbshZUvqC0NUgTlz8lqg.jpeg" /></figure><h3>What is Action Cable?</h3><blockquote>Action Cable seamlessly integrates WebSockets with the rest of your Rails application. — Rails</blockquote><p>If you are curious about the WebSocket protocol that Action Cable integrates, I wrote an <a href="https://medium.com/@Arockne/networking-introduction-to-websockets-7c0ffc3c2d6e">introduction</a> to the protocol.</p><h3>Before we begin</h3><p>We will be implementing the use of Action Cable in the chatroom application I made. If you would like to code along, go ahead and fork from the <a href="https://github.com/Arockne/ye-ole-chatterbox/tree/actioncable-blog">actioncable-blog</a> branch. We will be working in the Chatroom component within the client directory. Once the repository is forked and cloned, go ahead and run some commands.</p><pre>#The application assumes that bundler, npm, ruby, rails, and postgresql is installed</pre><pre><strong>Run these commands</strong>:<br>bundle install<br>rails db:create db:migrate db:seed<br>npm install --prefix client</pre><p>Side note: I may end up separating out some of the logic into separate components in the current working version of the application. There may be some react warnings for the time being.</p><h3>Action Cable Setup</h3><h4><strong>Route for Action Cable</strong></h4><p>The route that action cable uses by default is ‘/cable’ endpoint. We will not need to explicitly specify our route to utilize our websocket connection.</p><pre>URL:<br>ws://localhost:3000/cable</pre><p>If you would like to explicitly define the action cable route:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ef50d7aee9f031ee6c228b856f3ab9f/href">https://medium.com/media/6ef50d7aee9f031ee6c228b856f3ab9f/href</a></iframe><h4>Server Setup</h4><p>In the <strong>Gemfile</strong>, uncomment <a href="https://redis.io/"><strong>redis</strong></a> and run bundle install. If in the future you are planning on deploying to Heroku, this article will help clarify some configuration you may need to do.</p><h4>Client Setup</h4><p>Run this command in the client directory:</p><pre>npm install actioncable --save</pre><h3>Connecting to the websocket cable</h3><h4>Creating our ChatChannel</h4><p>In our root directory run:</p><pre>rails g channel Chat</pre><p>This command will generate channel files within our app folder. If you navigate into the channels/application_cable directory, there are two files:</p><ul><li>channel.rb</li><li>connection.rb</li></ul><p>The <strong>channel.rb</strong> file is the superclass of each channel that gets created. All shared logic between channels would go here.</p><p>The <strong>connection.rb</strong> file is where authorization and authentication logic lives. Currently the application has authentication setup elsewhere. We will only be setting up authorization to the Websocket connection.</p><h4>Authorizing connection request</h4><p>When you <strong>subscribe</strong> to a channel the authorization will trigger in the connection class. The <strong>Connection</strong> class responsibility is authorization and authentication. Currently the application has authentication setup in the SessionsController. We will only implement authorization within the Connection class and utilizing the session created through the SessionsController. We will want to set up a <strong>connect</strong> method. The connect method triggers when you attempt to subscribe to a channel. We will want to authorize the connection only if the user is logged in. Otherwise, we will want to reject the connection request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/099a83919a6ebe1077bcfbe8dfce7bba/href">https://medium.com/media/099a83919a6ebe1077bcfbe8dfce7bba/href</a></iframe><p><a href="https://api.rubyonrails.org/v7.0.2.2/classes/ActionCable/Connection/Identification/ClassMethods.html#method-i-identified_by">identified_by</a> allows us to reference current_user within our channels and find the specific connection again.</p><h4>Subscribing to ChatChannel via a specific room in client</h4><p>Let’s navigate into the chatroom component. First we need to import <strong>actioncable</strong> into our component.</p><pre>import Cable from &#39;actioncable&#39;<br>or<br>import ActionCable from &#39;actioncable&#39;</pre><p>Currently the entire chat application uses HTTP crud actions to get/update chatroom information. When we first navigate into a chatroom on the client when the application is running. The application will send a get request to ChatroomsController#show action. We will currently keep this logic, but what we will update is how the new messages are transmitted and received.</p><p>First we will need to set up our subscription to our ChatChannel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a835f90106e038f0efdc14e884a35675/href">https://medium.com/media/a835f90106e038f0efdc14e884a35675/href</a></iframe><pre>const consumer = Cable.createConsumer(`ws://${window.location.hostname}:3000/cable`)</pre><ul><li>This method allows us to set up our initial connection against the URL that we want to connect to</li><li>Usually the default argument to this method is ‘/cable’, but since our react application in development is running on a separate port, we will need to specify our URL: ws://${window.location.hostname}:3000/cable</li><li>Creating the <strong>consumer</strong> does not attempt to establish a connection until an attempt is made to subscribe to a channel</li></ul><pre>const subscription = consumer.subscriptions.create()</pre><ul><li>This <strong>subscriptions.create</strong> method allow us to <strong>subscribe</strong> to a channel through the <strong>consumer</strong> we have created</li><li>The <strong>subscriptions.create</strong> method takes two objects as arguments</li><li>The first argument is an object that is used to specify which channel we want to subscribe to. The channel property is required for connection. The room property is optional and allows us to be specific with the room we want to subscribe to. This object will also be the <strong>params</strong> to the channel we specify.</li><li>The second argument is an object of methods that allow us to get information from a broadcast and allows us to create and use custom methods defined in our channel</li><li>We will want to store this connection in state</li></ul><h4>Handling subscription within ChatChannel</h4><p>The subscribed/unsubscribed methods are generated with our channel generator method. What we will need to add is where we want to <strong>stream_from</strong> and where we want to <strong>stop_stream_from</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c2bb85e391b85bebcc51cac7f173c7a/href">https://medium.com/media/5c2bb85e391b85bebcc51cac7f173c7a/href</a></iframe><p>When we create a subscription, the subscribed method will get invoked and this is where we want to specify the channel or room we want to be connected to. In this <a href="https://blog.saeloun.com/2020/03/17/rails-adds-actioncable-channel-stop_stream_from-and-actioncable-channel-stop_stream_for-methods.html">blog</a>, the methods used to connect/disconnect in the subscribed/unsubscribed methods are explained in a concise way. Once the channel subscription methods have been setup, if you navigate into a chatroom within the browser, you will see the three-way-handshake in action in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*P2cKWUiHMJ4MvM0ZPHt_dA.png" /></figure><h3>Creating a full duplex communication</h3><h4>Client Side implementation</h4><p>How I am managing state within the Chatroom component is by using the useReducer hook. If you are curious or would like to know more, I <a href="https://medium.com/@Arockne/react-refactor-using-usereducer-hook-13add37f1068">blogged</a> about the process of implementing useReducer.</p><pre>case &#39;chatConnection&#39;: {<br>  return { ...state, chatConnection: action.payload}<br>}</pre><p>Let’s add the action type ‘chatConnection’ to the reducer function to update our connection state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bbe447ed6879e7d54be593298e7f348/href">https://medium.com/media/1bbe447ed6879e7d54be593298e7f348/href</a></iframe><p>Also, we will insert our chatConnection state to initialize to an object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e760a61539e2940340a1034aa05c8e7/href">https://medium.com/media/9e760a61539e2940340a1034aa05c8e7/href</a></iframe><p>Next we will dispatch the <strong>subscription</strong> to chatConnection:</p><pre>dispatch({ type: &#39;chatConnection&#39;, payload: subscription })</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e51c1e95450302d1eb6b69db16c04282/href">https://medium.com/media/e51c1e95450302d1eb6b69db16c04282/href</a></iframe><h4>Unsubscribe method</h4><p>Currently if you were to switch between the same chatrooms multiple times in the browser the server logs will show multiple connections to a chat room. This would create a bug where if a user sends a message, the message will be duplicated the amount of times a connection to a chatroom was established. To fix this temporarily, we can unsubscribe from a <strong>subscription connection</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb9fb00bbf2a03e3d8e650c6be46da75/href">https://medium.com/media/bb9fb00bbf2a03e3d8e650c6be46da75/href</a></iframe><pre>chatConnection.unsubscribe()</pre><ul><li>This method allows us to use the <strong>unSubscribed</strong> method in the ChatChannel</li></ul><p>Let’s now add the ability to receive messages from other users connected to the same channel or room.</p><h4>Received method</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7db1d61feecb6fb43911e312d061a3b1/href">https://medium.com/media/7db1d61feecb6fb43911e312d061a3b1/href</a></iframe><p>Whenever a message is <strong>broadcast</strong> from our back end whether from a controller action or channel method, we will receive the broadcasted message to the <strong>received</strong> method. In the defined <strong>received</strong> method, the state that is holding the messages for the chatroom will receive the messages automatically by dispatching new broadcasted messages from <strong>ActionCable.server.broadcast</strong>.</p><h4>Server Side Implementation</h4><p>First we will implement our message broadcast from our MessagesController#create action. Place this method after the creation of a message:</p><pre>ActionCable.server.broadcast( <br>  membership.name, <br>  MessageSerializer.new(message).as_json<br>)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe46907e1b6736180623d1bbe0f6e9c7/href">https://medium.com/media/fe46907e1b6736180623d1bbe0f6e9c7/href</a></iframe><pre>.broadcast()</pre><ul><li>The first argument to this method is the room/channel you would like to send this message to.</li><li>The second argument is the payload that you would like sent to that room/channel specified in the first argument.</li></ul><pre>MessageSerializer.new(message).as_json</pre><ul><li>if we want to use Active model serializer to serialize our message, we will need to explicitly create an instance of the message serializer, which will allow us to also include associations that were defined within the serializer</li></ul><p><strong>Commenting out setting new message coming from HTTP response:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81d460dd74518fe5259520ab515ebf82/href">https://medium.com/media/81d460dd74518fe5259520ab515ebf82/href</a></iframe><p>If the logic was not commented out, you will end up seeing two of the same messages on your end since the creation of our messages depends on a successful response. The chat is now a full duplex communication system.</p><h3>Refactoring to broadcast messages from ChatChannel</h3><p>Now that we have a full duplex communication working, let’s move the message broadcast logic to the ChatChannel and remove the broadcast from the MessagesController#create action. The first thing we will use is the <strong>send</strong> method from our subscription connection.</p><h4>Send Method</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfe11d19512bbecf1ffd06d3cf1bd128/href">https://medium.com/media/cfe11d19512bbecf1ffd06d3cf1bd128/href</a></iframe><p>With this method we will replace the dispatch method we commented out to send messages to other channels. The send method requires an object be passed in, otherwise an error will pop up in the terminal. The object that is passed into the send method will be transported to the <strong>receive</strong> method in the ChatChannel. If the receive method was not defined, the terminal will let us know that it’s looking for a receive method within the ChatChannel when using the send method.</p><h4>Receive Method</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c64ca96375ecaee0c1ab538fbd22336/href">https://medium.com/media/5c64ca96375ecaee0c1ab538fbd22336/href</a></iframe><p>The receive method is where we will be <strong>broadcasting</strong> our message after we create our message. There are few things we have access to like the params from our subscription, the payload transported to this method, current_user and some other things.</p><h4>Removing http POST request for messages</h4><p>Within the client directory, navigate to the Messenger component and find the handleNew function. Currently when we create a new message, we will be creating two copies of the same message. We will want to either comment out or remove the fetch request. Place the message handlers to the top of the function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eaa26fcc3aedbeba6088ce7b1f33044/href">https://medium.com/media/5eaa26fcc3aedbeba6088ce7b1f33044/href</a></iframe><h3>Resources</h3><ul><li><a href="https://www.npmjs.com/package/actioncable">actioncable</a></li><li><a href="https://guides.rubyonrails.org/action_cable_overview.html">Action Cable Overview - Ruby on Rails Guides</a></li><li><a href="https://blog.saeloun.com/2020/03/17/rails-adds-actioncable-channel-stop_stream_from-and-actioncable-channel-stop_stream_for-methods.html">Rails has added support in Action Cable to unsubscribe from specific stream</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95b261a4d203" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React: Refactor Using useReducer Hook]]></title>
            <link>https://medium.com/@Arockne/react-refactor-using-usereducer-hook-13add37f1068?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/13add37f1068</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-hook-usereducer]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 15:09:36 GMT</pubDate>
            <atom:updated>2022-02-15T01:58:10.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*j1Wlh2ZJ17VR-MTXsynmMA.jpeg" /><figcaption>Image by: <a href="https://www.flickr.com/photos/bowtoo/4233736193/">Tim Bouwer</a></figcaption></figure><h3>What is the useReducer hook?</h3><p>This hook offers an alternative to the <a href="https://reactjs.org/docs/hooks-reference.html#usestate">useState</a> hook. The <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">useReducer</a> hook allows us another way to work with state in our component. Which allows us to change multiple state variables alongside each other. This becomes useful when you want to update multiple pieces of state simultaneously and optimize for needless re-renders.</p><h3>Before we begin</h3><p>We will be refactoring using the chatroom application I made. If you would like to code along, go ahead and fork from the <a href="https://github.com/Arockne/ye-ole-chatterbox/tree/useReducer-blog">useReducer-blog</a> branch. We will be working in the Chatroom component within the client directory. Once the repository is forked and cloned, go ahead and run some commands.</p><pre>#The application assumes that bundler, npm, ruby, rails, and postgresql is installed</pre><pre><strong>Run these commands</strong>:<br>bundle install<br>rails db:create db:migrate db:seed<br>npm install --prefix client</pre><p>Otherwise, the full implementation can be found in the <a href="https://github.com/Arockne/ye-ole-chatterbox/tree/main">main</a> branch.</p><h3>Refactoring using the useReducer hook</h3><h4>To get started:</h4><pre><strong>Run these commands in separate windows:</strong><br>rails s<br>npm start --prefix client</pre><p>You’ll be navigated to a login screen, you can either create an account or login using a pre-made account created through seed data.</p><h4>Refactoring Chatroom Component State:</h4><p>If not done so, let’s navigate into the Chatroom component. There will be two state variables that we will be refactoring using useReducer hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e72243158530289a9c20d6cd4eaa8847/href">https://medium.com/media/e72243158530289a9c20d6cd4eaa8847/href</a></iframe><h4>useReducer set up:</h4><p>First let’s go ahead and import <strong>useReducer</strong> from react and remove the useState import. Then remove the two state variables and replace with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2ebab87b8c35593b5ab744bf15e8cf4/href">https://medium.com/media/e2ebab87b8c35593b5ab744bf15e8cf4/href</a></iframe><p>The location of the reducer function will be above the Chatroom component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6639069c66c9521051ff1e4fa390ff40/href">https://medium.com/media/6639069c66c9521051ff1e4fa390ff40/href</a></iframe><p>When invoking useReducer, the two argument values are:</p><ul><li>Reducer function</li><li>Initial state value(s)</li></ul><p>The <strong>reducer function</strong> is where our setter logic will be contained. The two parameters that will be held by our reducer function will be our current <strong>state</strong> and the <strong>action</strong> that will be passed from our <em>dispatch</em> function. Depending<strong><em> </em></strong>on our action, we will be assigning/reassigning multiple pieces of state based on a condition. Currently we are just returning the current state.</p><p>The <strong>initial state</strong> value(s) can be any primitive or non-primitive value. In our case we will be assigning our initial state to be an object with two properties.</p><p>After invoking <strong>useReducer</strong>, the value returned will be an array with two values:</p><ul><li>State</li><li>Dispatch function</li></ul><p>The <strong>state</strong> value is where our current state will be contained.</p><p>The <strong>dispatch</strong> function is how we will explicitly state the action we want executed. We will do this by passing an object with two properties to dispatch:</p><ul><li>type</li><li>payload</li></ul><p>The <strong>type</strong> property allows us tell our reducer function based on the type of action for what values in state we want reassigned.</p><p>The <strong>payload</strong> property will hold any value we want passed to the reducer function for assignment/reassignment. Sometimes the payload property is unnecessary if there is not a value to pass for assignment/reassignment, <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">react</a> has a good example of this.</p><h4>Commenting out setter logic from useState:</h4><p>We will be using most of the setter logic within our reducer function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61cc01f6cc4aa769acee1347da48d170/href">https://medium.com/media/61cc01f6cc4aa769acee1347da48d170/href</a></iframe><h4>Creating setter logic within our reducer function:</h4><p>First we are going to set up a conditional block depending on the <strong>type</strong> property from our action. We will also define a couple of conditions based on requesting our chatroom. In these conditions we will be explicitly assigning specific state values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ce5ded62e26f9857b6eb8c70baa8403/href">https://medium.com/media/6ce5ded62e26f9857b6eb8c70baa8403/href</a></iframe><p>The dispatch function as the name implies allows us to dispatch a message and pass along data to our reducer function. Then our reducer function uses this message to assign specific state with or without the payload.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faf99b5f67730cd1e7a871827dc23523/href">https://medium.com/media/faf99b5f67730cd1e7a871827dc23523/href</a></iframe><p>Here we have replaced our setter logic with a function that has more meaning.</p><p>Let’s add the setter logic from our CRUD functions to our reducer function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc01e4d65c46c83f0a57211ec036ce34/href">https://medium.com/media/bc01e4d65c46c83f0a57211ec036ce34/href</a></iframe><p>Finally, let’s dispatch our messages for our functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13dbc671ca4946294dfd87c62b3a91a7/href">https://medium.com/media/13dbc671ca4946294dfd87c62b3a91a7/href</a></iframe><p>All of our crud actions will be working as they were before.</p><p>Thank you for reading.</p><h3>Resources</h3><p><a href="https://reactjs.org/docs/hooks-reference.html#usereducer">Hooks API Reference - React</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13add37f1068" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Networking: Introduction to WebSockets]]></title>
            <link>https://medium.com/@Arockne/networking-introduction-to-websockets-7c0ffc3c2d6e?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c0ffc3c2d6e</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[duplex-communication]]></category>
            <category><![CDATA[computer-networking]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 14:57:09 GMT</pubDate>
            <atom:updated>2022-02-18T01:33:40.988Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*CvnWilhM1fqR_p36elMyhg.png" /></figure><h3>What is a WebSocket?</h3><p>A WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. -Wikipedia</p><h3>WebSocket URI</h3><pre>WebSocket:<br>&quot;ws:&quot; &quot;//&quot; host [ &quot;:&quot; port ] path [ &quot;?&quot; query ]</pre><pre>WebSocket Secure:<br>&quot;wss:&quot; &quot;//&quot; host [ &quot;:&quot; port ] path [ &quot;?&quot; query ]</pre><p>WebSocket protocol defaults to <strong>port 80</strong> for ws and <strong>port 443</strong> for wss.</p><h4>Example:</h4><p>ws://example.com:800/chat</p><p>wss://example.com:6000/chat</p><h3>What is full-duplex communication?</h3><p>First let’s try to understand what is a duplex.</p><p>A <strong>duplex</strong> is a communications system that is bidirectional in nature. Meaning that two or more connected devices can communicate with one another in both directions. Depending on the type of duplex system, the way the communication operates changes. There are two types of duplex systems:</p><ol><li>Half-duplex</li><li>Full-duplex</li></ol><h4>Half Duplex</h4><p>In a half-duplex system, when a device sends a message, the device or devices on the receiving end must wait until the message has been successfully received before being able to send a message themselves. An example of this would be the HTTP request response cycle.</p><h4>Full Duplex</h4><p>In a full-duplex system, two or more devices can receive and send messages simultaneously. Many examples of this is used in phones, remote desktop connections, chatrooms, etc…</p><h3>How does the WebSocket protocol operate?</h3><p>A Websocket connection allows real-time data transfer between the client and the server without making a ton of request. How the WebSocket protocol does this is through a TCP connection which allows messages to stream on top of TCP. The connection, once established, allows data to transfer easily between multiple devices.</p><p>Before a stable connection is made between the client and the server, the client will initiate a three-way handshake. A <strong>handshake</strong> is a signal between two devices or programs used to authenticate and coordinate.</p><h4>The client will send an HTTP upgrade request:</h4><pre>GET /chat HTTP/1.1<br>        Host: server.example.com<br>        Upgrade: websocket<br>        Connection: Upgrade<br>        Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==<br>        Origin: http://example.com<br>        Sec-WebSocket-Version: 13<br></pre><p>The <strong>Upgrade: websocket</strong> and <strong>Connection: Upgrade </strong>headers let the server know that the client is requesting a websocket connection.</p><p>The <strong>Sec-WebSocket-Key</strong> header is a part of the information received by the server to ensure that the request received is a valid websocket opening handshake. The server will also use this information to prove to the client that the handshake has been received successfully.</p><p>The <strong>origin</strong> header is included and usually sent by default from all browsers to allow the server to protect against cross-origin request that are unauthorized.</p><h4>Once the server has received the client request, the server will send:</h4><pre>HTTP/1.1 101 Switching Protocols<br>        Upgrade: websocket<br>        Connection: Upgrade<br>        Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=<br>        Sec-WebSocket-Protocol: chat</pre><p>The server will take a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#:~:text=A%20universally%20unique%20identifier%20(UUID,(GUID)%20is%20also%20used.&amp;text=Adoption%20of%20UUIDs%20is%20widespread,for%20parsing%20their%20textual%20representation.">UUID</a> of <strong><em>258EAFA5-E914–47DA-95CA-C5AB0DC85B11 </em></strong>append to<strong><em> </em></strong>the <strong>Sec-WebSocket-Key </strong>to form the string:</p><blockquote>dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914–47DA-95CA-C5AB0DC85B11</blockquote><p>Then will apply a <a href="https://en.wikipedia.org/wiki/SHA-1">SHA-1</a> hashing function to the string. The server will then take this hashed string and return the value within <strong>Sec-WebSocket-Accept</strong> header.</p><p>If the status code from the server is any other status code than 101, the handshake will not complete. If the <strong>Sec-WebSocket-Accept</strong> header is missing or the header does not have the expected value then the connection will not be established. When the server sends back a response with the same <strong>Upgrade: websocket</strong> and <strong>Connection: Upgrade</strong> headers, this will complete the upgrade request and establish a connection.</p><h4>Once the connection has been established:</h4><p>The communication between the client and the server becomes full-duplex communication. In the example of a chatroom, when a message is sent in a chatroom, the message itself is sent in a <a href="https://en.wikipedia.org/wiki/Payload_(computing)">payload</a> with some <a href="https://en.wikipedia.org/wiki/Overhead_(computing)">protocol overhead</a> to the server. Like <a href="https://en.wikipedia.org/wiki/Network_packet">packets</a>, the message itself can be split between multiple data <a href="https://en.wikipedia.org/wiki/Frame_(networking)">frames</a>. The server can send that message to other connected clients that are connected to that chatroom.</p><h3>Resources</h3><ul><li><a href="https://en.wikipedia.org/wiki/Handshaking">Handshaking - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Transmission_Control_Protocol">Transmission Control Protocol - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">Hypertext Transfer Protocol - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/HTTP/1.1_Upgrade_header">HTTP/1.1 Upgrade header - Wikipedia</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc6455">RFC 6455: The WebSocket Protocol</a></li><li><a href="https://en.wikipedia.org/wiki/Duplex_(telecommunications)#FULL-DUPLEX">Duplex (telecommunications) - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/WebSocket">WebSocket - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c0ffc3c2d6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails: Nesting Data with Custom Serializers using Active Model Serializers]]></title>
            <link>https://medium.com/@Arockne/rails-nesting-data-with-custom-serializers-using-active-model-serializers-a2e51d4ad21b?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e51d4ad21b</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[active-model-serializer]]></category>
            <category><![CDATA[serializers]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 02:07:20 GMT</pubDate>
            <atom:updated>2022-01-26T02:54:32.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*nDMORJDaAPgC8vwc.png" /><figcaption><a href="https://hazelcast.com/glossary/serialization/">https://hazelcast.com/glossary/serialization/</a></figcaption></figure><h3>What is serialization?</h3><p>The process of translating a data structure or object state into a format that can be stored or transmitted and reconstructed later. This data structure or object is usually converted to a JSON or XML format. For our purposes we will be serializing our ruby hash into JSON.</p><h3>How active model serializer works</h3><p><a href="https://github.com/rails-api/active_model_serializers/tree/0-10-stable">Active Model Serializers(AMS)</a> uses the same mantra as Rails, convention over configuration. Which means Active Model Serializers follow the same naming conventions when it comes to class names and file names. When setting up your serializers, you will want to have the same singular name as your associated model. With this convention, the serializer that is associated will be used implicitly on serialization. For example, in the case of a chat application, there is a Chatroom model and the respective serializer name will be ChatroomSerializer. When it comes to serializing nested data, we will be breaking some conventions.</p><h3>Getting started with active model serializers</h3><p>If you’d like to follow <a href="https://github.com/Arockne/ye-ole-chatterbox/tree/serializer-blog">along</a>, go ahead and fork from the branch serializer-blog.</p><h4>To get started:</h4><pre>#This application assumes that bundler, ruby, rails, and postgresql is installed</pre><pre>Run these commands:</pre><pre>bundle install<br>rails db:create db:migrate db:seed</pre><h4>Add Active Model Serializers:</h4><pre>bundle add active_model_serializers</pre><h3>Serializing with conventions</h3><p>Before we get into the thick of it, let’s look at how active model serializer is used when following conventions by creating a serializer for our Chatroom.</p><h4>Run the following command:</h4><pre>rails g serializer Chatroom</pre><p>This command will generate the serializers directory for you if the directory did not exist. The command will also nest the generated serializer within the serializers directory.</p><h4>Looking at our generated Serializer:</h4><pre>class ChatroomSerializer &lt; ActiveModel::Serializer<br>  attributes :id<br>end</pre><p>Here rails has defined an <strong>attributes</strong> method for us. This attributes method allows us to specify the attributes we would like to be serialized in our response.</p><h4>Defining our attributes:</h4><p>Lets start up our rails server with:</p><pre>rails s</pre><p>We will be working the with the show and index routes:</p><pre>Index:<a href="http://127.0.0.1:3000/api/chatrooms"><br>http://127.0.0.1:3000/api/chatrooms</a></pre><pre>Show:<br>http://127.0.0.1:3000/api/chatrooms/:id</pre><p>We will only use these routes to retrieve data. While the server is running, you can either retrieve this information through the browser or something like <a href="https://www.postman.com/">postman</a>. As we request information with one of the two paths, you’ll notice that each request only contains an <strong>id attribute</strong>.</p><p><strong><em>Response:</em></strong></p><pre>Show: { &quot;id&quot;: 1 }</pre><pre>Index: <br>[<br>  { &quot;id&quot;: 1 },<br>  { &quot;id&quot;: 2 },<br>  { &quot;id&quot;: 3 },<br>  { &quot;id&quot;: 4 },<br>  { &quot;id&quot;: 5 }<br>]</pre><p>The reason for this is that we only specified the id attribute to be serialized with our response</p><p>Lets now add in some attributes:</p><pre>class ChatroomSerializer &lt; ActiveModel::Serializer<br>attributes :id, :name, :image_url, :bio<br>end</pre><p>In our response, we will now see: <strong>id, name, image_url, and bio</strong> attributes. We can also include custom queries from our Model, custom methods from our serializer, and use association methods. The association method will only work if the respective model has defined the association macro.</p><h3>Using Custom Serializers</h3><p>From here on on out we will mostly be using our show route:</p><pre>Show:<br>http://127.0.0.1:3000/api/chatrooms/:id</pre><p>Lets generate our custom show serializer with some other serializers:</p><pre>Run these commands:<br>rails g serializer ChatroomShow<br>rails g serializer Message<br>rails g serializer User</pre><pre><strong>OR these to include the attributes as well:</strong><br>rails g serializer ChatroomShow name<br>rails g serializer Message created_at content<br>rails g serializer User username image_url</pre><h4>Adding a custom serializer:</h4><p>By breaking conventions we will need to specify our serializer within our show action in the chatrooms controller.</p><pre>def show<br>  chatroom = Chatroom.find(params[:id])<br>  render json: chatroom, status: :ok, <br>  <strong>serializer: ChatroomShowSerializer</strong><br>end</pre><p>If you wanted to specify the custom serializer on an array of data we can specify like so:</p><pre>def index<br>  chatrooms = Chatroom.all<br>  render json: chatrooms, status: :ok, <br>  <strong>each_serializer: ChatroomShowSerializer</strong><br>end</pre><h3>Serializing nested data</h3><h4>Specify attributes and associations in each serializer:</h4><p>ChatroomShowSerializer:</p><pre>class ChatroomShowSerializer &lt; ActiveModel::Serializer<br>  attributes :id, :name</pre><pre>  has_many :members<br>  has_many :messages<br>end</pre><p>MessageSerializer:</p><pre>class MessageSerializer &lt; ActiveModel::Serializer<br>  attributes :id, :created_at, :content<br>  <br>  belongs_to :user<br>end</pre><p>UserSerializer</p><pre>class UserSerializer &lt; ActiveModel::Serializer<br>  attributes :id, :username, :image_url<br>end</pre><blockquote>To note:</blockquote><blockquote>The <strong>members association</strong> will use UserSerializer because the source is user</blockquote><pre>class Chatroom &lt; ApplicationRecord</pre><pre>has_many :chatroom_memberships, dependent: :destroy<br><strong>has_many :members, through: :chatroom_memberships, source: :user</strong><br>has_many :messages, dependent: :destroy<br>end</pre><p>You can also specify a custom serializer for an association within our serializers like so:</p><pre>belongs_to :user, serializer: UserSerializer</pre><p>After requesting from the show route you will notice that the association <strong>belongs_to :user</strong> within the <strong>MessageSerializer</strong> is not being serialized. The reason for this is by default, Active Model Serializer only serialize the association <strong>one level deep</strong>. To get around this we need to include the attributes and their children in the controller.</p><h4>Including nested associations:</h4><p>We will need to change how our show route renders our serializer by including the attributes and their association.</p><pre>def show<br>  chatroom = Chatroom.find(params[:id])<br>  render json: chatroom, status: :ok, <br>  serializer: ChatroomShowSerializer, <br>  <strong>include: [&#39;messages&#39;, &#39;messages.user&#39;, &#39;members&#39;]<br></strong>end<br></pre><p>Thank you for reading,</p><p>If you would like to see how I implemented the serializers further within my chatting application, go ahead and head over to the <a href="https://github.com/Arockne/ye-ole-chatterbox/tree/main">main</a> branch.</p><h3>Resources</h3><ul><li><a href="https://github.com/rails-api/active_model_serializers/tree/0-10-stable">GitHub - rails-api/active_model_serializers at 0-10-stable</a></li><li><a href="https://github.com/Arockne/ye-ole-chatterbox/tree/serializer-blog">GitHub - Arockne/ye-ole-chatterbox at serializer-blog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e51d4ad21b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Brief Introduction to CORS]]></title>
            <link>https://medium.com/@Arockne/a-brief-introduction-to-cors-1e30183ae339?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e30183ae339</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[back-end-web-development]]></category>
            <category><![CDATA[cors]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Wed, 10 Nov 2021 21:35:08 GMT</pubDate>
            <atom:updated>2021-11-29T16:22:45.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*zeAthmX6SaEN5bDo.jpg" /></figure><h4>What is CORS?</h4><blockquote><strong>Cross-origin resource sharing</strong> (<strong>CORS</strong>) is a mechanism that allows restricted <a href="https://en.wikipedia.org/wiki/Web_resource">resources</a> on a <a href="https://en.wikipedia.org/wiki/Web_page">web page</a> to be requested from another <a href="https://en.wikipedia.org/wiki/Domain_name">domain</a> outside the domain from which the first resource was served. -Wikipedia</blockquote><blockquote>CORS is an HTTP-header based mechanism that allows a server to indicate any origins other than its own from which a browser should permit loading resources-MDN</blockquote><p>CORS is what allows a client to make a cross-origin request to a server. Cross-origin meaning, getting information from another domain that is not the domain where the request came from. The server from which you made a request to will either accept or deny your request based on <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers">HTTP headers</a>, which will then tell you if your origin is permitted or not. Depending on the request, if the request is simple, like a <em>get</em> request, then the headers are automatically set by the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent">user-agent</a>. If the request was a preflight request, then the browser will send the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS">OPTIONS</a> method with the request to determine if that request is permitted. Regardless of the type of request made, CORS follows a same-origin policy, which allows only specific origins to make any request to the server, unless specific CORS headers are specified.</p><h4>What is an origin?</h4><p>An <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin"><strong><em>origin</em></strong></a> is typically defined by a protocol, domain, and a port. Here is an example:</p><blockquote><a href="http://example.com/">http://example.com</a>:76</blockquote><blockquote><strong>Protocol</strong>: http, <strong>Domain</strong>: example.com, <strong>Port</strong>:76</blockquote><h4>Same-origin policy</h4><blockquote>The <strong>same-origin policy</strong> is a critical security mechanism that restricts how a document or script loaded by one <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">origin</a> can interact with a resource from another origin.</blockquote><blockquote>-MDN</blockquote><p>Based on the same-origin policy, CORS will reject any origin that does not have specific permissions from the server. An origin making a request must match an origin that has permission, otherwise CORS will reject the request and give a CORS error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*IkzYughfN2J32H8vBgLA3Q.png" /></figure><p>To allow the public in general to request information from your server, you can specify the origins allowed to be a wildcard(*). For security reasons, you should always specify the origin(s) that you want to be able to request information from your server. The origins have to match for the request to be accepted or denied, here are some examples of origin matching:</p><blockquote>Origin1: <a href="http://example.com:90/drivers">http://example.com:90/drivers</a></blockquote><blockquote>Origin2: <a href="http://example.com:90/boots">http://example.com:90/boots</a></blockquote><blockquote>Origin3: <a href="https://example.com:76/shops">https://example.com:76/shops</a></blockquote><blockquote>Origin4: <a href="http://example.com/boots">http://example.com/boots</a></blockquote><blockquote>Origin5: <a href="http://shops.com:90/items">http://shops.com:90/items</a></blockquote><p><strong>Origin1</strong> will match with <strong>Origin2</strong> since the origins are the same. <strong>Origin3</strong> will not match with any other origin since the protocols are not the same. <strong>Origin4</strong> will not match with any other origin since the port number is not specified. <strong>Origin5</strong> will not match any other origin because of a different domain name.</p><p><strong><em>Aside</em></strong>: If no port is specified, the port for HTTP will default to a port number of 80. HTTPS will default to 443. Also, when Internet Explorer does same-origin checks, IE considers two origins with the same protocol and domain to be the same origin.</p><h4>Resources</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing (CORS) - HTTP | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin - MDN Web Docs Glossary: Definitions of Web-related terms | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">Same-origin policy - Security | MDN</a></li><li><a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing#CORS_vs_JSONP">Cross-origin resource sharing - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e30183ae339" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Implemented Client Side Routing Into My React Application]]></title>
            <link>https://medium.com/@Arockne/how-i-implemented-client-side-routing-into-my-react-application-cda54c2d43d9?source=rss-322a735e6272------2</link>
            <guid isPermaLink="false">https://medium.com/p/cda54c2d43d9</guid>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Daniel Calvin]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 01:37:12 GMT</pubDate>
            <atom:updated>2021-11-09T01:33:56.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*VTEybiqhlAvhK4pyBZzxcw.jpeg" /></figure><p>When I first started learning Client Side Routing, I felt as if I stepped into a maze for the first time. As I continued into this maze I became disoriented and confused. Here I will clear up some confusion that I had working with <a href="https://reactrouter.com/web/guides/quick-start&#39;">react router</a> and some things regarding routing in general. We will also work together on implementing some react router components in a react application. The version of react router we are using is from version 5.</p><h4>What is Routing?</h4><blockquote><strong>Routing</strong> is the process of selecting a path for traffic in a <strong>network</strong> or between or across multiple <strong>networks</strong>.</blockquote><p>I like to think of routing as stepping onto a path that has been mapped out to get to a specific destination. While walking down that path there are other possible paths that you can go down to get to your destination.</p><h4>What is Server Side Routing?</h4><p>In terms of routing, all the routing is done on the server side and what was requested will be displayed by the client. When a user types something in the address bar or clicks on a link, the action of doing so will result in an HTTP GET request. If the server is reached, it will send an index.html page and all the information in relation to that page. If the user clicks on a link within that address or manually enters the address, a server will send a response.</p><h4>What is Client Side Routing?</h4><p>In terms of routing, most routing typically gets handled by the client. With client side routing when you initially make a HTTP GET request, the entirety of the web page will be loaded into the client. Whenever a user clicks on a link that routes somewhere within the page, the routing will be handled by the client without making an additional HTTP GET request to the server. Typically client side routing is used in single page applications.</p><h4>Getting Started</h4><p><a href="https://github.com/Arockne/blog-example-inventory-tracker">If you would like to follow along or solve this on your own.</a> What this application does is track inventory expenses. Whenever you add an item to the inventory it will update the totals related to that item quantity and price.</p><h4>Here is some deliverables that you may be implement:</h4><blockquote>Initialize React Router to be used by the entire application</blockquote><blockquote>Create links to home, inventory, and new in NavBar component</blockquote><blockquote>Create routes from NavBar links in App component</blockquote><blockquote>Reuse the ItemForm component to edit an item</blockquote><blockquote>Whenever an item is added to inventory or edited, the page will route back to inventory</blockquote><h4>BrowserRouter</h4><p>BrowserRouter is what initializes the use of react router in our application in a browser environment which helps keep the <em>User Interface </em>be in sync with the URL. BrowserRouter is like getting a blank piece of paper to start drawing out a map for your components. In the current state of our application we do not have any routing capabilities and where we need to add BrowserRouter is at the top level of our application in <em>index.js</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*samGcMyzGzcj6gKxt737jg.png" /></figure><h4>NavLink/Link</h4><blockquote>Provides declarative, accessible navigation around your application.</blockquote><p>In the context of a map, the Link will be the road that leads to a destination. Link and NavLink provide the same functionality. The only difference is that you can add an activeStyle attribute to NavLink. When the url matches the NavLink end point it will activate the activeStyle. Let’s implement out the NavBar component using NavLink.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*-sw3mwoy976A5hSIEO-uSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44GfojsZs6P_Yj733hSYUA.png" /></figure><p>To give some context on the attributes:</p><blockquote><strong>exact</strong> is a boolean value that is set to true when the prop is passed in and tells the browser to only match this path exactly. This helps with activeStyle to make sure that “/” does not match “/new” or “/inventory” when active.</blockquote><blockquote><strong>to</strong> is the destination end point that you want the webpage to go to.</blockquote><blockquote><strong>style/activeStyle</strong> is the style of links that are inactive or active</blockquote><p>Whenever you click on one of the links in the NavBar you should see a change in the URL like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*Pa6j8sW7QdYhRo7Pp0j_gg.png" /><figcaption>Current URL: <strong>localhost:3000</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*MtSZGut1gusQqdUiM8KcZA.png" /><figcaption>Current URL: <strong>localhost:3000/inventory</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*kt9IRhoIH6WQG0CnsXcIWQ.png" /><figcaption>Current URL: <strong>localhost:3000/new</strong></figcaption></figure><h4>Route component with Switch</h4><p>To keep going with our map metaphor, if you decide to travel on a specific path, once you have reached the end point you will be able to see the surrounding area at that destination. The Route is the destination and the surrounding area is the children within Route. Those children can also contain Routes as well. Switch restricts you from going down multiple paths at the same time.</p><p>One way to think of the Switch is like a switch statement in Javascript.</p><pre>switch(path) {<br>  case &#39;/&#39;:<br>    &lt;Home /&gt;<br>    break;<br>  case &#39;/inventory&#39;:<br>    &lt;InventoryPage /&gt;<br>    break;<br>  case &#39;/new&#39;:<br>    &lt;ItemForm /&gt;<br>    break;<br>  default:<br>    &lt;h1&gt;404 Not Found!&lt;/h1&gt;<br>}</pre><p>Let’s implement our Switch and Route in our App component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*hdwKV-TwZOQ8WjNncxdrRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*1YM3AHBD68XPlO8Lnbsz0Q.png" /></figure><p>Whenever you click on a link in the NavBar it should render components that are children to a specific Route that matches the current URL. I also added a wildcard path <strong>“/*” </strong>to match any other url that was not specified.</p><p><strong>Component Reuse</strong></p><p>Let’s say that when we click a link to edit the current item, we want to reuse the ItemForm component in a way that would not result in us adding another item and not going down the same path as “/new”. Instead, when we click the link within the item card it will result going down a path like “/edit” and the formData will become the current item data. This can be a little tricky, but the components we will be using to implement will be App, Item, and ItemForm. The React Router hooks we will be using are <strong>useParams</strong> and <strong>useRouteMatch</strong></p><p>Let’s start by adding a route path to ‘edit/:name’ to the App component. The “:name” is going to be the property key of the object that is returned when invoking the hook useParams from React Router. Instead of passing in <strong>handleAddItem</strong> to the param <strong>onAddItem</strong>, we will instead pass <strong>handleItemEdit</strong> to <strong>onAddItem</strong> for some reusability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*ZgDN0_E8T-o5IgX5sQ7Oag.png" /></figure><p>Now that we have our Route, let’s now implement our Link to edit an item. I decided to add the edit Link to an icon within the card header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*2m8yAinrnA0uwJKGy3YqAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*DczV0SL0kjd4ctV73GFS6A.png" /></figure><p>When we link to the end point of “./edit/${name}”, <strong>the value of “name” will be the property value of the name property within the useParams hook.</strong></p><p>When you click the edit link it should result in having the name of the inventory item be the end point of the url like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*97CJwKNTyNlvntV-xtIk8w.png" /></figure><p>Now that we have our Link working. Let’s now implement our ItemForm component to be reusable to add items and to edit items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*v7C1W0odJsTEHc6ed7eS2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*1TOCaCkIY8G3C1h6Ew5BMA.png" /></figure><p>How we implement this is by using the value from useParams hook. We use the value of “name” to see if the item is contained in inventory. If it is, we need to use the useEffect hook to run whenever a variable changes state that is depended by the useEffect hook by placing the variables in the dependencies array.</p><p>What the conditional (name &amp;&amp; containsItem) is checking to see if the name is defined and also that the name is contained within inventory. If the name does exist in inventory, the form data will be set to that item data.</p><p>When I did not have the else statement attached to the if statement within useEffect I ran into a bug where if you were to click the <strong>New</strong> link in NavBar, the data within the form would still be there from clicking to edit an item. The else statement is there to make sure if we leave the edit without making changes the form data will become empty input fields.</p><p>The condition at the end is to make sure to give the user a message if they manually type in the url to edit an item that does not exist in inventory.</p><p><strong>useHistory Hook</strong></p><p>This hook returns an object that lets you work with a users web history in their current tab. How we will use this hook is when a user edits an item or adds an item to inventory, the user will be moved to ‘/inventory’ end point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*l9h69kEXn6C9Z2zYGivSNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*K2CzXtIt7PhwxbNXAnA1Eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*1zgkYjvW6cQtdJ27V2mjKQ.png" /></figure><p>Here, we are taking the optimistic approach when our form data gets submitted successfully. On a success we will use the useHistory object to push the user to ‘/inventory’. This will place the current address on top of the history stack.</p><h4>Summary</h4><p>In our map context using React Router, BrowserRouter was the map itself, Link/NavLink is the direction to the destination, Route is what you see once you get to that destination, useHistory is the tracked steps taken to get to the destination.</p><h4>Resources</h4><p><a href="https://reactrouter.com/web/guides/philosophy">React Router</a></p><p><a href="https://github.com/Arockne/blog-example-inventory-tracker">Example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cda54c2d43d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>