<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Matthew Kohn</title>
    <description>The latest articles on DEV Community by Matthew Kohn (@matthewkohn).</description>
    <link>https://dev.to/matthewkohn</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F471033%2F11a2fad7-f2a1-4093-a570-9ccc47098cc2.jpeg</url>
      <title>DEV Community: Matthew Kohn</title>
      <link>https://dev.to/matthewkohn</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/matthewkohn"/>
    <language>en</language>
    <item>
      <title>Missing GitHub Contributions? Double Check Configurations.</title>
      <dc:creator>Matthew Kohn</dc:creator>
      <pubDate>Mon, 07 Nov 2022 01:01:26 +0000</pubDate>
      <link>https://dev.to/matthewkohn/missing-github-contributions-double-check-configurations-1ihm</link>
      <guid>https://dev.to/matthewkohn/missing-github-contributions-double-check-configurations-1ihm</guid>
      <description>&lt;p&gt;After recently graduating from &lt;a href="https://flatironschool.com/welcome-to-flatiron-school/software-engineering/"&gt;Flatiron School's Software Engineering program&lt;/a&gt;, I noticed the contributions graph in my &lt;a href="https://github.com/matthewkohn"&gt;GitHub profile&lt;/a&gt; was looking deceivingly weak.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cHSYQkDd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b35arqubc0908sblrkza.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cHSYQkDd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b35arqubc0908sblrkza.png" alt="GitHub contributions before fix" width="528" height="213"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This was incredibly frustrating for me, because I spent a lot of time over the last year on various projects &amp;amp; labs that this graph didn't seem to account for. &lt;/p&gt;

&lt;p&gt;Every green dot here was either a contribution from a new repo, or a cloned repo from a lab. No other commit I made on any of my projects showed up here.&lt;/p&gt;

&lt;p&gt;I pored over &lt;a href="https://stackoverflow.com/"&gt;StackOverflow&lt;/a&gt; articles and the &lt;a href="https://docs.github.com/en"&gt;GitHub Guides&lt;/a&gt; looking for an answer. I found one article that I found useful titled &lt;a href="https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-github-profile/managing-contribution-settings-on-your-profile/why-are-my-contributions-not-showing-up-on-my-profile"&gt;"Why are my contributions not showing up on my profile?"&lt;/a&gt;, which explains what counts as a contribution:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Commits will appear on your contributions graph if they meet all of the following conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The email address used for the commits is associated with your account on GitHub.com.&lt;/li&gt;
&lt;li&gt;The commits were made in a standalone repository, not a fork.&lt;/li&gt;
&lt;li&gt;The commits were made:

&lt;ul&gt;
&lt;li&gt;In the repository's default branch&lt;/li&gt;
&lt;li&gt;In the gh-pages branch (for repositories with project sites)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is great, but I needed help troubleshooting my situation.&lt;/p&gt;

&lt;p&gt;That's when I called up the big guns, &lt;a class="mentioned-user" href="https://dev.to/stevewhitmore"&gt;@stevewhitmore&lt;/a&gt;. He was nice enough to screenshare over a zoom call to troubleshoot why my commits weren't showing up as contributions. It was helpful talking out the problem and getting a second set of eyes on it.&lt;/p&gt;

&lt;p&gt;After trying out a few things to eliminate what didn't work, such as changing my SSH key or testing commits from different branches in both of our accounts, we found the solution. &lt;/p&gt;




&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EVq8aqG3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s01mkrwds0ngyn63vs32.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EVq8aqG3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s01mkrwds0ngyn63vs32.png" alt="Unsplash image of hands holding a lightbulb" width="468" height="376"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Photo by &lt;a href="https://unsplash.com/@pavement_special?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Riccardo Annandale&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/solution?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Solution
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;It turns out, I had two different email addresses set up locally and in my GitHub account.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In my terminal, I checked my locally configured email address with &lt;code&gt;git config --global user.email&lt;/code&gt;. This revealed my locally configured email was set to my hotmail account, while my GitHub profile's email was set to my gmail account. &lt;/p&gt;

&lt;p&gt;Rookie mistake, easy to fix.&lt;/p&gt;




&lt;h3&gt;
  
  
  1. Configure GitHub Email Locally
&lt;/h3&gt;

&lt;p&gt;First, I made sure to set up my local machine's GitHub configured email to the same email address in my GitHub profile, my gmail account. In my terminal, I used:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git config --global user.email ko.....@gmail.com&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I tested out to see if I could push up a local commit by adding a blank line to a README.md I recently pushed, then committing it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git add README.md
git commit -m "test commit"
git push
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In my GitHub account, I confirmed this commit was received, and a green contribution box showed up for this commit.&lt;/p&gt;




&lt;h3&gt;
  
  
  2. Add Email Used in Past Commits to GitHub Settings
&lt;/h3&gt;

&lt;p&gt;Next, I went into my GitHub Settings.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--M04WKU-h--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zqid7oa7bg0jnngyyr4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--M04WKU-h--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zqid7oa7bg0jnngyyr4.png" alt="GitHub settings dropdown" width="244" height="639"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;On the left side of the settings page, under 'Access', click on the 'Emails' tab. This is where I confirmed my gmail account was my primary email address. &lt;/p&gt;

&lt;p&gt;I then added the hotmail account I was using locally up until now as an additional email address.&lt;/p&gt;

&lt;h4&gt;
  
  
  Before:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XLOSHvq9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywlz7rqrrhkxbeubyfyu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XLOSHvq9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywlz7rqrrhkxbeubyfyu.png" alt="Image description" width="624" height="271"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  After:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LI8jx6Sz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtwn5gk8b6gq25aexh1b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LI8jx6Sz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtwn5gk8b6gq25aexh1b.png" alt="After email settings" width="624" height="219"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once I verified my additional email address by following the link sent by GitHub, I navigated back to my &lt;a href="https://github.com/matthewkohn"&gt;GitHub profile&lt;/a&gt; contributions page. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--reWv6tN8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zm0bdairdmh26splh5fh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--reWv6tN8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zm0bdairdmh26splh5fh.png" alt="GitHub contributions after fix" width="526" height="221"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, &lt;strong&gt;all&lt;/strong&gt; contributions I made (past commits, new repos, and forks) over the past year show up on my contributions graph. &lt;/p&gt;

&lt;p&gt;🎉&lt;/p&gt;

&lt;p&gt;What a relief! This is a much better representation of my engagement with coding during school while working part-time.&lt;/p&gt;




&lt;h3&gt;
  
  
  In Closing,
&lt;/h3&gt;

&lt;p&gt;This was a solution to my specific problem of contributions not appearing in my GitHub profile. &lt;/p&gt;

&lt;p&gt;You may or may not have the same problem, if you did I hope this helps. If not, keep digging for the solution, and don't be afraid ask for help if you get stuck. I believe in you.&lt;/p&gt;

&lt;p&gt;Huge shoutout to &lt;a class="mentioned-user" href="https://dev.to/stevewhitmore"&gt;@stevewhitmore&lt;/a&gt; for your help. Thank you, I might have never figured it out without you. &lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>github</category>
      <category>codenewbie</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Keeping track of React state with useContext()</title>
      <dc:creator>Matthew Kohn</dc:creator>
      <pubDate>Thu, 06 Oct 2022 02:01:34 +0000</pubDate>
      <link>https://dev.to/matthewkohn/keeping-track-of-react-state-with-usecontext-27bo</link>
      <guid>https://dev.to/matthewkohn/keeping-track-of-react-state-with-usecontext-27bo</guid>
      <description>&lt;p&gt;&lt;a id="top"&gt;&lt;/a&gt;In my time learning React at &lt;a href="https://flatironschool.com/about-us/" rel="noopener noreferrer"&gt;Flatiron School&lt;/a&gt;, I came to really like the &lt;a href="https://reactjs.org/docs/context.html" rel="noopener noreferrer"&gt;useContext hook&lt;/a&gt;. I remember at first, though, the concept of context was a little confusing. &lt;/p&gt;

&lt;p&gt;I'm excited to share what I've learned, and I hope it helps you.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;What is &lt;em&gt;useContext&lt;/em&gt;?&lt;/li&gt;
&lt;li&gt;
Example for setting up &lt;em&gt;useContext&lt;/em&gt;

&lt;ul&gt;
&lt;li&gt;Make a context file&lt;/li&gt;
&lt;li&gt;Wrap Provider around highest level component&lt;/li&gt;
&lt;li&gt;Using &lt;em&gt;useContext&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Conclusion&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;This article walks through how to set up and use a Context component in a React application, using functional component syntax. This article assumes you know the basics of React, and moves past some concepts quickly. Note the links abound for elaboration, if you'd like to dig deeper into React Context.&lt;/p&gt;

&lt;p&gt;It's &lt;a href="https://reactjs.org/docs/thinking-in-react.html" rel="noopener noreferrer"&gt;important to understand&lt;/a&gt; how hooks, props &amp;amp; state works with functional components before you dive into using context to control global state.&lt;/p&gt;

&lt;h2&gt;
  
  
  A couple brief definitions to warm us up:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://reactjs.org/docs/hooks-overview.html" rel="noopener noreferrer"&gt;Hooks:&lt;/a&gt; functions that let you “hook into” React state and lifecycle features from function components.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://reactjs.org/docs/components-and-props.html" rel="noopener noreferrer"&gt;Props:&lt;/a&gt; arbitrary properties that are passed down from parent to child components.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.digitalocean.com/community/tutorials/how-to-manage-state-on-react-class-components" rel="noopener noreferrer"&gt;State:&lt;/a&gt; the structure that keeps track of how data changes over time.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  What is &lt;em&gt;useContext()&lt;/em&gt;?&lt;a id="what"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;useContext&lt;/strong&gt; hook is a way to manage global state without needing to pass state as props. When your component tree starts to grow, you might notice certain state that you need among sibling components, like a student's id or items in a cart. &lt;/p&gt;

&lt;p&gt;One solution might be to move that state to the nearest parent component, but that might be all the way up to the App component, and you might have to &lt;a href="https://www.geeksforgeeks.org/what-is-prop-drilling-and-how-to-avoid-it/" rel="noopener noreferrer"&gt;prop-drill&lt;/a&gt; to manage that state. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faoo1ry0d3c79v7q2nijc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faoo1ry0d3c79v7q2nijc.png" alt="Basic Component Tree"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A better solution might be to &lt;a href="https://www.youtube.com/watch?v=3XaXKiXtNjw" rel="noopener noreferrer"&gt;re-compose&lt;/a&gt; the structure of your component tree and pass state as props, but that might not be a reasonable solution depending on the complexity of your app.&lt;/p&gt;

&lt;p&gt;This is where useContext() might come in handy. By keeping track of state in context &amp;amp; passing that context to the components can make your life a whole lot easier.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy18jgs2jtxp8k5j782vd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy18jgs2jtxp8k5j782vd.png" alt="Component tree with context"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Example for setting up &lt;em&gt;useContext()&lt;/em&gt;&lt;a id="example"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;br&gt;
(skip to see result)&lt;/p&gt;

&lt;p&gt;If you'd like to follow along, make sure you have a text editor and command line prompt handy. &lt;/p&gt;

&lt;p&gt;Create a new React App called whatever you want, like "student-library".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app student-library
cd student-library
npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  1. Make a context file&lt;a id="make"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;Let's say we're trying to keep track of &amp;amp; update data about hypothetical students in our app.&lt;/p&gt;

&lt;p&gt;Let's start writing code. Here's how I like to structure my files in my React App.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foz92bkgpxcxdsajem5a4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foz92bkgpxcxdsajem5a4.png" alt="File Structure for React App"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;i. From your app's '&lt;code&gt;/src&lt;/code&gt;', folder, create a folder called '&lt;code&gt;/context&lt;/code&gt;', then from there make a file called "&lt;code&gt;StudentContext.jsx&lt;/code&gt;".&lt;/p&gt;




&lt;p&gt;ii. At the top of the file, import React, and start a function component called &lt;code&gt;StudentProvider&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function StudentProvider() {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;iii. Now, use the &lt;a href="https://contactmentor.com/react-createcontext-example/" rel="noopener noreferrer"&gt;&lt;code&gt;createContext()&lt;/code&gt;&lt;/a&gt; function built into React to create a Context object. &lt;br&gt;
Outside of/above the function declaration, make StudentContext:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const StudentContext = React.createContext();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As &lt;a href="https://reactjs.org/docs/context.html" rel="noopener noreferrer"&gt;React Docs&lt;/a&gt; say, &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Every Context Object comes with a Provider React component that allows consuming components to subscribe to context changes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We will use this Provider in the next steps to give other components access to our context's state.&lt;/p&gt;




&lt;p&gt;iv. Return &lt;code&gt;StudentContext.Provider&lt;/code&gt; inside the function component, wrapped around the special &lt;a href="https://www.netlify.com/blog/2020/12/17/react-children-the-misunderstood-prop/" rel="noopener noreferrer"&gt;&lt;code&gt;children&lt;/code&gt;&lt;/a&gt; props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function StudentProvider({ children }) {
  return (
    &amp;lt;StudentContext.Provider&amp;gt;
      { children }
    &amp;lt;/StudentContext.Provider&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;v. At the end of the file, export &lt;code&gt;StudentContext&lt;/code&gt; and &lt;code&gt;StudentProvider&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export { StudentContext, StudentProvider }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;vi. Now, set up the student's state. Import the &lt;code&gt;useState&lt;/code&gt; hook:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from "react";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;vii. Make &lt;code&gt;student&lt;/code&gt; state inside the function before the return statement, with an initial value of &lt;code&gt;null&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [student, setStudent] = useState(null);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;viii. Save the state &amp;amp; its setter in a variable, we'll call &lt;code&gt;value&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const value = { student, setStudent };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;ix. Finally, pass this value as props in the &lt;code&gt;StudentContext.Provider&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;StudentContext.Provider value={ value }&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  Here's the complete file for &lt;code&gt;StudentContext.jsx&lt;/code&gt;:&lt;a id="result"&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;(back to beginning of example)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 'StudentContext.jsx'
-----
import React, { useState } from 'react';
const StudentContext = React.createContext();

function StudentProvider({ children }) {
  const [student, setStudent] = useState(null);
  const value = { student, setStudent };
  // console.log('student from StudentContext: ', student)
  return (
    &amp;lt;StudentContext.Provider value={ value }&amp;gt;
      { children }
    &amp;lt;/StudentContext.Provider&amp;gt;
  )
}

export { StudentContext, StudentProvider }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  2. Wrap Provider around highest level component&lt;a id="wrap"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;According to &lt;a href="https://reactjs.org/docs/context.html#reactcreatecontext" rel="noopener noreferrer"&gt;React Docs&lt;/a&gt;, &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Remember, the Provider is “providing” access to the Context component (and the state or other variables it may hold) anywhere you need to invoke it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question&lt;/strong&gt;: Which components will you need to set or access &lt;code&gt;student&lt;/code&gt; and &lt;code&gt;setStudent&lt;/code&gt; in your app? &lt;/p&gt;

&lt;p&gt;Find the top-most parent component they all have in common. This is where we will use our &lt;code&gt;StudentProvider&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Since our context is helping us with global state, and for the sake of this example, we're moving all the way up to index.js in the '&lt;code&gt;/src&lt;/code&gt;' folder. You can place this anywhere that works for your app, just make sure it's "above" anywhere you'll need it in the component hierarchy.&lt;/p&gt;

&lt;p&gt;Import &lt;code&gt;StudentProvider&lt;/code&gt; and wrap it around the root component, which in this case is &lt;code&gt;&amp;lt;App/&amp;gt;&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 'index.js'
-----
import React from 'react';
import ReactDOM from 'react-dom/client';
import { StudentProvider } from './context/StudentContext';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  &amp;lt;StudentProvider&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/StudentProvider&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, any child of the &lt;code&gt;&amp;lt;App /&amp;gt;&lt;/code&gt; component is able to import StudentContext if they need to.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. Using &lt;em&gt;useContext()&lt;/em&gt;&lt;a id="using"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;Now you are able to access and set student state anywhere in your app.&lt;/p&gt;

&lt;p&gt;Let's say you are using student data stored on an API. Make a new file under '&lt;code&gt;/src/components/&lt;/code&gt;' called &lt;code&gt;Student.jsx&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;i. Start by importing &lt;code&gt;React&lt;/code&gt;, &lt;code&gt;useContext&lt;/code&gt; and &lt;code&gt;StudentContext&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useContext } from 'react';
import { StudentContext } from '../context/StudentContext';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;ii. Destructure values inside the component function by passing &lt;code&gt;StudentContext&lt;/code&gt; to the &lt;code&gt;useContext()&lt;/code&gt; hook.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Student () =&amp;gt; {
  const { student, setStudent } = useContext(StudentContext);
  return (&amp;lt;&amp;gt;&amp;lt;/&amp;gt;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From here, you can fetch data from an API and store it with &lt;code&gt;setStudent&lt;/code&gt; inside a &lt;code&gt;useEffect&lt;/code&gt; hook, or create a form a user can fill out and save a form data object with &lt;code&gt;setStudent&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Once you set your state with the Context Component you made, you can use that data however you want, passing the &lt;code&gt;student&lt;/code&gt; variable to this or any other component in your app with the useContext hook. &lt;/p&gt;

&lt;p&gt;You could use it to display a name, provide authorization to view hidden components, or store a schedule, shopping cart, or profile page, to name a few examples. It's really up to you from here what you want to do.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion&lt;a id="conclusion"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;Using Context is easy &amp;amp; convenient once you know how it's set up and how it's used. You can keep track of errors, themes, authorization codes, or really anything you might need to keep track of global state.&lt;/p&gt;

&lt;p&gt;Keep in mind, anytime you update Context State, the component using that state will re-render. If this isn’t the behavior you want, maybe a &lt;a href="https://reactjs.org/docs/hooks-reference.html" rel="noopener noreferrer"&gt;useMemo or useRef&lt;/a&gt; hook might be a better choice. &lt;/p&gt;

&lt;p&gt;Please note: It is advised to use useContext sparingly because of performance issues when your app scales. Only use it if you need it. &lt;/p&gt;

&lt;p&gt;Some React devs think that useContext is bad, for reasons &lt;a href="https://blog.thoughtspile.tech/2021/10/04/react-context-dangers/" rel="noopener noreferrer"&gt;worth considering&lt;/a&gt;. I like using it for themes &amp;amp; authentication in smaller dynamic apps, like my personal projects.&lt;/p&gt;

&lt;p&gt;In the end, it's up to you to decide how to structure your app and make it respond to student interactions how you see fit. This is just one of many ways to keep track of state in a dynamic React application.&lt;/p&gt;

&lt;p&gt;I hope this helps, and I wish you well. Happy coding!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>tutorial</category>
      <category>beginners</category>
      <category>react</category>
    </item>
    <item>
      <title>Cookies &amp; Sessions in Rails</title>
      <dc:creator>Matthew Kohn</dc:creator>
      <pubDate>Sun, 31 Jul 2022 00:34:52 +0000</pubDate>
      <link>https://dev.to/matthewkohn/cookies-sessions-in-rails-54b8</link>
      <guid>https://dev.to/matthewkohn/cookies-sessions-in-rails-54b8</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi0n7l4fndpvoeagzl7j1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi0n7l4fndpvoeagzl7j1.png" alt="Photo by &amp;lt;a href="&gt;&lt;/a&gt;SJ . on &lt;a href="https://unsplash.com/s/photos/cookies?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;br&gt;
  "/&amp;gt;&lt;a id="top"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  What are Cookies &amp;amp; Sessions in Rails?
&lt;/h2&gt;

&lt;p&gt;I've learned a lot about cookies &amp;amp; sessions while creating my Phase 4 React/Rails project at &lt;a href="https://flatironschool.com" rel="noopener noreferrer"&gt;Flatiron School&lt;/a&gt;, and I'm excited to share some of it with you.&lt;/p&gt;

&lt;p&gt;This article aims to explain what &lt;a href="https://api.rubyonrails.org/v5.2.1/classes/ActionDispatch/Cookies.html" rel="noopener noreferrer"&gt;cookies&lt;/a&gt; &amp;amp; &lt;a href="https://guides.rubyonrails.org/security.html#sessions" rel="noopener noreferrer"&gt;sessions&lt;/a&gt; are in regard to the &lt;a href="https://en.wikipedia.org/wiki/Request%E2%80%93response" rel="noopener noreferrer"&gt;request/response&lt;/a&gt; cycle, what they help us do, and how to configure a Rails API so you can use them in your application. I've included many links to resources throughout this reading if there are any terms you'd like to learn more about.&lt;/p&gt;
&lt;h3&gt;
  
  
  Table of Contents
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;What are Cookies?&lt;/li&gt;
&lt;li&gt;What are Sessions?&lt;/li&gt;
&lt;li&gt;
How to start building a Rails API that uses cookies &amp;amp; sessions

&lt;ul&gt;
&lt;li&gt;File Structure&lt;/li&gt;
&lt;li&gt;Middleware&lt;/li&gt;
&lt;li&gt;Include Cookies in ApplicationController&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Conclusion and Next Steps&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Adding State to an API Request
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.cloudflare.com/learning/ddos/glossary/hypertext-transfer-protocol-http/" rel="noopener noreferrer"&gt;HTTP&lt;/a&gt; is a &lt;a href="https://www.interviewbit.com/blog/stateful-vs-stateless/" rel="noopener noreferrer"&gt;stateless&lt;/a&gt; protocol. HTTP servers receive and process requests, return data, then forgets about it.&lt;br&gt;
Cookies help us (the client) make stateful HTTP requests by letting the server remember us with the information it stores.&lt;/p&gt;
&lt;h2&gt;
  
  
  What are cookies?&lt;a id="cookies"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.rubydoc.info/docs/rails/3.2.8/ActionDispatch/Cookies" rel="noopener noreferrer"&gt;Cookies&lt;/a&gt; are collections of data, usually key:value pairs, that are created by a web server when someone asks for access to their website. When the server computes what it needs to and sends a response, it also sends cookies in HTTP headers to the client, and are stored by the user's browser on the hard drive.&lt;/p&gt;

&lt;p&gt;Cookies are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Small: no more than 4kb &lt;/li&gt;
&lt;li&gt;Not complex: a collection of name:value pairs, not programs or models&lt;/li&gt;
&lt;li&gt;Domain-specific: other websites have no way of reading them&lt;/li&gt;
&lt;li&gt;Temporary by nature: they can expire, or get updated frequently.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cookies allow a user to persist data across requests, which is used for a &lt;a href="https://techcommunity.microsoft.com/t5/iis-support-blog/session-state-and-session-cookies-best-practices/ba-p/714333" rel="noopener noreferrer"&gt;variety of UI needs&lt;/a&gt;. Cookies keep us on the same page, in more ways than one.&lt;/p&gt;

&lt;p&gt;Examples of what cookies might &lt;a href="https://homepage.cs.uri.edu/faculty/wolfe/book/Readings/R09%20Links/cookie.htm" rel="noopener noreferrer"&gt;keep track of&lt;/a&gt; are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An expiration date/time for automatic logout, requiring a new login, creating a new session &amp;amp; new set of cookies&lt;/li&gt;
&lt;li&gt;Pages within a site you've visited&lt;/li&gt;
&lt;li&gt;Letting the server know if you're a first-time user&lt;/li&gt;
&lt;li&gt;Your flight itinerary&lt;/li&gt;
&lt;li&gt;Previously inputted contact information&lt;/li&gt;
&lt;li&gt;Your zip code for local weather information&lt;/li&gt;
&lt;li&gt;Remembering what's in your shopping cart so you can sleep on it...&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's say a user goes to a website they've been to before, like the one we're on right now. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;When you type &lt;code&gt;https://dev.to/&lt;/code&gt; into your browser and hit &lt;code&gt;enter&lt;/code&gt;, your browser begins to send a &lt;strong&gt;request&lt;/strong&gt; to the Web server for the page. First, the browser looks on your hard drive for a cookie file that &lt;code&gt;dev.to&lt;/code&gt; may have set. If it finds a cookie, it will send the encrypted cookie data along with the URL to &lt;code&gt;dev.to&lt;/code&gt;'s server. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The server for &lt;code&gt;dev.to&lt;/code&gt; will decrypt those cookies (if any), and send back a &lt;strong&gt;response&lt;/strong&gt; to the client with program files that may apply uniquely to that user. For example, my cookies allow me to view &lt;a href="https://dev.to"&gt;&lt;code&gt;https://dev.to/&lt;/code&gt;&lt;/a&gt; in dark mode by default when I go to their website.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you'd like to take a peek at your own cookies, pull up your browser's &lt;a href="https://developer.chrome.com/docs/devtools/storage/cookies/" rel="noopener noreferrer"&gt;Dev tools&lt;/a&gt; (right-click then -&amp;gt; inspect), choose the Application tab, and check out the cookies you have for the website you're on. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F80xmalv59xasxb1h61ps.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F80xmalv59xasxb1h61ps.png" alt="Screenshot of Chrome Dev Tools showing cookies data in the Application tab"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You might see a long string of random characters, numbers, and symbols that you won't be able to read, and if you try to change them (not recommended), the website's server won't accept them anymore. You won't break anything, but you might have to reload your screen.&lt;/p&gt;

&lt;p&gt;Here's an example of what a random cookie from my browser looks right right now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Cookie name:value
__cf_bm: x1MTF2K9gphl51GldO4Dq1TxBY5CXFO0YRXs9_zQjTc-1659208596-0-AfIDBDqPcHBuY2y1l3pO3jQaoORPrRrlw5NJP0flJJdPyOZQvKWS8loytli0XA0DNGuUE+jdyvcOGF8o4R9+23Bf1dM8SHGkspE8Sfsmeq3G
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is pretty hard to read because it's been encrypted &amp;amp; signed by Rails. By the time anyone (or thing) thinks to figure out what it means, the server won't remember what it means. Let's find out why that is.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd2rnfocyglybybqe8to3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd2rnfocyglybybqe8to3.png" alt="![Photo by &amp;lt;a href="&gt;&lt;/a&gt;Thalia Ruiz on &lt;a href="https://unsplash.com/s/photos/cookies?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;br&gt;
  ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zyziethtykjevzrrrhdk.png)&lt;br&gt;
 "/&amp;gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  What are sessions?&lt;a id="sessions"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;So how are cookies secure? I know one solution: Rails to the rescue!&lt;/p&gt;

&lt;p&gt;Instead of sending cookies in plain text, we can use Rails to sign a special cookie only it knows how to unscramble known as a &lt;a href="https://guides.rubyonrails.org/action_controller_overview.html#session" rel="noopener noreferrer"&gt;session&lt;/a&gt; using the &lt;code&gt;session&lt;/code&gt; method. Session can store any simple Ruby object, and behaves like a hash: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;session[:user_id]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Application information can be securely stored in the user's browser because sessions encrypts and signs those cookies.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A Rails session stores a unique, &lt;a href="https://en.wikipedia.org/wiki/Identity-based_encryption" rel="noopener noreferrer"&gt;cryptographically signed &amp;amp; encrypted ID&lt;/a&gt; (not the actual session_id, for security reasons) on a small block of data. The Rails app responsible can decrypt and read the contents of that cookie if it's sent back. &lt;/li&gt;
&lt;li&gt;Sessions should be used to store all session data on the cookie that's sent to the user along with all of the other files their browser needs to run the app.&lt;/li&gt;
&lt;li&gt;When the user interacts with the app, the session will last as long as they're logged in, allowing them to do whatever they're &lt;a href="https://auth0.com/docs/get-started/identity-fundamentals/authentication-and-authorization" rel="noopener noreferrer"&gt;authorized&lt;/a&gt; to do. &lt;/li&gt;
&lt;li&gt;When they log out, the session "ends" and their cookie data is obsolete. Cookies live on your computer until you delete them.&lt;/li&gt;
&lt;li&gt;Sessions shouldn't be used to store highly confidential information, complex objects, or large amounts of data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;How you decide to use sessions to control your app's behavior is up to you.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqopigmxc53avdl385u18.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqopigmxc53avdl385u18.png" alt="Photo by &amp;lt;a href="&gt;&lt;/a&gt;Nathan Dumlao on &lt;a href="https://unsplash.com/s/photos/cookies?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;br&gt;
  "/&amp;gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  How to start building a Rails API with Postgres that uses cookies &amp;amp; sessions&lt;a id="how_to"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Setup&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;If you'd like to try this out yourself, get a code editor like &lt;a href="https://code.visualstudio.com/download" rel="noopener noreferrer"&gt;VS Code&lt;/a&gt;, and make sure you have the following installed:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;    &lt;a href="https://www.ruby-lang.org/en/documentation/installation/" rel="noopener noreferrer"&gt;Ruby 2.7.4&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;    &lt;a href="https://guides.rubyonrails.org/v5.0/getting_started.html" rel="noopener noreferrer"&gt;Rails 7.0.3&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;    &lt;a href="https://www.postgresql.org/download/" rel="noopener noreferrer"&gt;Postgresql 14.4&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Create&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Once those have been installed, create a new Rails API from your command line:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;$ rails new example-app --api --database=postgresql&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;    You can name your app anything you want.&lt;/li&gt;
&lt;li&gt;    The &lt;code&gt;--api&lt;/code&gt; flag means you're creating a Rails app with no View or ERB, just the modules to build a relational database using the M and the C in &lt;a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noopener noreferrer"&gt;MVC&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;    To use a test-suite like Rspec, add a &lt;code&gt;-T&lt;/code&gt; flag to the end if you want.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Explore&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Now, navigate to your new app &lt;/p&gt;

&lt;p&gt;&lt;code&gt;cd example-app&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;and open the app in your code editor to begin the fun part with&lt;/p&gt;

&lt;p&gt;&lt;code&gt;code .&lt;/code&gt;&lt;/p&gt;


&lt;h3&gt;
  
  
  File Structure&lt;a id="files"&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;The highlights of your file structure are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;./app&lt;/code&gt;, where the core functionality of the app lives, such as Models, Controllers, Views, and Serializers.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;./bin&lt;/code&gt; has built-in Rails tasks you probably won't need to worry about starting out.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;./config&lt;/code&gt; manages settings that control environment settings, modules that need to load on initialization, database settings, app routes, etc.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;./db&lt;/code&gt; holds migrations, seed data and the schema for your database.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;./lib&lt;/code&gt; holds custom Rake tasks.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;./log&lt;/code&gt; holds logs for debugging purposes.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Gemfile&lt;/code&gt; contains all gems included with the application. This is where you can add your own gems.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Gemfile.lock&lt;/code&gt; shouldn't be edited. This is created when you run &lt;code&gt;bundle install&lt;/code&gt; and contains every Gem's dependencies &amp;amp; associated versions. If you need to, you can delete this file and run &lt;code&gt;bundle install&lt;/code&gt; again to make sure you have the right gems installed according to your Gemfile.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;README.md&lt;/code&gt; documents the details of the application, and can (and should) be as thorough as you want.&lt;/li&gt;
&lt;/ul&gt;


&lt;h3&gt;
  
  
  Middleware&lt;a id="middle"&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;Unfortunately, cookie middleware isn't automatically included in our Rails API. Without them, no cookies. Before we hop into sessions &amp;amp; cookies, we need to configure our rails application to use them.&lt;/p&gt;

&lt;p&gt;Open &lt;code&gt;./config/application.rb&lt;/code&gt; and add a couple pieces of middleware. Here's what it should look like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F08q91q0vjpbi9kfkedol.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F08q91q0vjpbi9kfkedol.png" alt="Application config file"&gt;&lt;/a&gt;&lt;br&gt;
And here's what you need to add:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# config/application.rb
module MyApp
  class Application &amp;lt; Rails::Application
    config.load_defaults 6.1
    config.api_only = true

    # Must add these lines!
    config.middleware.use ActionDispatch::Cookies
    config.middleware.use ActionDispatch::Session::CookieStore

    # Use SameSite=Strict for all cookies to help protect against CSRF
    config.action_dispatch.cookies_same_site_protection = :strict
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://guides.rubyonrails.org/rails_on_rack.html#action-dispatcher-middleware-stack" rel="noopener noreferrer"&gt;&lt;code&gt;config.middleware.use ActionDispatch::Cookies&lt;/code&gt;&lt;/a&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Lets us use cookies&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://api.rubyonrails.org/classes/ActionDispatch/Session/CookieStore.html" rel="noopener noreferrer"&gt;&lt;code&gt;config.middleware.use ActionDispatch::Session::CookieStore&lt;/code&gt;&lt;/a&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Gives us access to the methods in Rails' CookieStore&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://web.dev/samesite-cookies-explained/" rel="noopener noreferrer"&gt;&lt;code&gt;config.action_dispatch.cookies_same_site_protection = :strict&lt;/code&gt;&lt;/a&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This line adds a little security, only allowing us to accept cookies from applications running on the same domain as ours (like running a Rails &amp;amp; React project from the same domain)&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  Include Cookies in ApplicationController&lt;a id="include"&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;(back to top)&lt;/p&gt;

&lt;p&gt;Finally, in order to use this we need to configure our most parent controller, ApplicationController, and instruct it to use cookies so the rest of our controllers have access to them. At the top of the file, &lt;a href="https://guides.rubyonrails.org/action_controller_overview.html#cookies" rel="noopener noreferrer"&gt;include it&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/controllers/application_controller.rb
class ApplicationController &amp;lt; ActionController::API
  include ActionController::Cookies
  ...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm07enrhwropmgasg1iia.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm07enrhwropmgasg1iia.png" alt="Photo by &amp;lt;a href="&gt;&lt;/a&gt;Erol Ahmed on &lt;a href="https://unsplash.com/s/photos/cookies?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;br&gt;
  "/&amp;gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  In Conclusion&lt;a id="conclusion"&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;(back to top)&lt;br&gt;
Nice work! That's it for this step. Now your app can use sessions &amp;amp; cookies.&lt;/p&gt;

&lt;p&gt;That was a lot! And there's so much more to learn, but there always is, and you're off to a good start. Take your time practicing, reading the docs, and navigating error messages. It's worth it, I promise.&lt;/p&gt;

&lt;p&gt;From here you can run &lt;code&gt;bundle install&lt;/code&gt; to install your gems, then &lt;code&gt;rails s&lt;/code&gt; to start up your rails server. Then, you'll need to set up your &lt;a href="https://flatironschool.com/blog/an-epic-adventure-how-to-create-sessions-in-rails/" rel="noopener noreferrer"&gt;Users and Sessions controllers&lt;/a&gt;, and continue to build an app with the &lt;a href="https://medium.com/@ashleymcolletti/add-authentication-to-your-rails-app-with-bcrypt-a53917252159" rel="noopener noreferrer"&gt;"BCrypt" gem for authorization&lt;/a&gt;, create &lt;a href="https://guides.rubyonrails.org/association_basics.html" rel="noopener noreferrer"&gt;associations&lt;/a&gt;, &lt;a href="https://guides.rubyonrails.org/active_record_basics.html" rel="noopener noreferrer"&gt;models&lt;/a&gt;, &lt;a href="https://guides.rubyonrails.org/action_controller_overview.html" rel="noopener noreferrer"&gt;controllers&lt;/a&gt;, &lt;a href="https://medium.com/@maxfpowell/a-quick-intro-to-rails-serializers-b390ced1fce7" rel="noopener noreferrer"&gt;serializers&lt;/a&gt;, and &lt;a href="https://edgeguides.rubyonrails.org/active_record_migrations.html" rel="noopener noreferrer"&gt;migrations&lt;/a&gt;. There's a lot to do still, but you can do it.&lt;/p&gt;

&lt;p&gt;As parting friendly advice, do yourself a favor:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Use a diagram app like &lt;a href="https://app.diagrams.net/" rel="noopener noreferrer"&gt;drawio&lt;/a&gt; or &lt;a href="https://dbdiagram.io/home" rel="noopener noreferrer"&gt;DB Diagram&lt;/a&gt;, or a pencil &amp;amp; paper, and plan out your &lt;a href="https://blog.crisp.se/2016/01/25/henrikkniberg/making-sense-of-mvp" rel="noopener noreferrer"&gt;MVP&lt;/a&gt; before you code anything else!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;While it's not necessary, it's highly recommended to think through the purpose of your api, the table associations and how they will manage the database's data, password management, and what endpoints and routes you want the user to use from the frontend. &lt;/p&gt;

&lt;p&gt;Take it from me, &lt;em&gt;it will save you a lot of time&lt;/em&gt; if you plan your app from top to bottom before you start coding.&lt;/p&gt;

&lt;p&gt;Thank you for reading this far, I hope it helps. If there's anything I missed, please feel free to add it in the comments. &lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>rails</category>
      <category>postgres</category>
      <category>codenewbie</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Ruby Enumerators- Syntax Basics</title>
      <dc:creator>Matthew Kohn</dc:creator>
      <pubDate>Fri, 03 Jun 2022 22:22:38 +0000</pubDate>
      <link>https://dev.to/matthewkohn/ruby-enumerators-syntax-basics-1cmh</link>
      <guid>https://dev.to/matthewkohn/ruby-enumerators-syntax-basics-1cmh</guid>
      <description>&lt;p&gt;Ruby is a fun language to learn. It's easy to use, and the syntax is straightforward and more intuitive than other programming languages. Despite this, it's capable of building vastly complex programs. &lt;/p&gt;

&lt;p&gt;In Ruby, almost everything is an object. All of these objects can have data and behaviors. Objects in the form of arrays and hashes can be given their own properties and actions, known as methods, that help us manipulate data and give objects the behaviors we want them to have. &lt;br&gt;
Enumerators are one type of method that give us fun and powerful ways to manage our data so we can focus on building cool things.&lt;/p&gt;
&lt;h3&gt;
  
  
  Understanding Ruby Basics
&lt;/h3&gt;

&lt;p&gt;According to Ruby documentation, an &lt;a href="'https://ruby-doc.org/core-2.7.3/Enumerable.html'"&gt;enumerator&lt;/a&gt; "provides collection classes with several traversal and searching methods, and with the ability to sort".&lt;br&gt;
In other words, enumerators are methods that "enumerate", or go one-by-one, over every element of a collection, helping us to view, manipulate, or sort arrays and hashes.&lt;/p&gt;

&lt;p&gt;Enumerators are chained to an array or hash using dot notation, and take a block of code as an argument that encapsulates what the enumerator is supposed to do with each element. This block is a chunk of code between curly braces {} (for simple, single-line blocks), or between "do" and "end" keywords. &lt;br&gt;
It takes one arbitrary element in the pipes || knows as a block parameter, that represents each element from the array. You can call the value in the pipes anything you want.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;titles = books.collect do |b|
  b[:title]
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or, for single-line blocks:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;titles = books.collect {|b| b[:title]}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don't already know, here's a brief summary of what I mean by arrays and hashes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="'https://ruby-doc.org/core-2.7.0/Array.html'"&gt;Arrays&lt;/a&gt; are ordered collections of strings, numbers, booleans, or even other arrays or hashes, wrapped in square brackets and separated by commas. Every element in an array is indexed, with the first element starting at index 0, the second element at index 1, and so on.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="'https://ruby-doc.org/core-3.1.1/Hash.html'"&gt;Hashes&lt;/a&gt; are collections of key: value pairs wrapped in curly brackets and separated by commas, where keys are commonly represented with &lt;a href=""&gt;"symbols"&lt;/a&gt;, and values can be any data type.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Practice For Yourself
&lt;/h3&gt;

&lt;p&gt;If you'd like to follow along with the examples, make sure you have Ruby installed. Since there are several ways to install Ruby, check out the &lt;a href=""&gt;installation guide&lt;/a&gt;. Once installed, you can play with Ruby code in your command line prompt by typing &lt;code&gt;irb&lt;/code&gt; and press &lt;code&gt;enter&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This brings you to a built-in playground for running Ruby, and your prompt should look something like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;2.7.4 :001 &amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Good to Know Moving Forward
&lt;/h3&gt;

&lt;p&gt;Since the Ruby language was designed to be easy to understand, and is inspired by several other programming languages, many enumerators have aliases that do the exact same thing as each other. For example, "map" and "collect" are functionally equivalent. It doesn't matter which one you use, just be sure to use one or the other to be consistent in your code.&lt;/p&gt;

&lt;p&gt;Also note that the "#" symbol before anything in Ruby isn't active code, it's just a comment that will be ignored by your computer.&lt;/p&gt;

&lt;p&gt;Our enumerator examples will use this array of hashes I've called "hackers", with each hash containing made-up information we can play with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;hackers = [ 
  { 
    name: "Matt",
    favorite_food: "tacos",
    favorite_language: "Ruby",
    years_coding: 3
  },
  {
    name: "Angie",
    favorite_food: "chocolate",
    favorite_language: "JavaScript",
    years_coding: 10
  },
  {
    name: "Joey",
    favorite_food: "broccoli",
    favorite_language: "Python",
    years_coding: 6
  }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Common Array Enumerables
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href=""&gt;&lt;strong&gt;EACH&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The &lt;code&gt;.each&lt;/code&gt; enumerator allows us to loop through items in an array.&lt;br&gt;
It doesn't return anything and doesn't change the array, but allows us to loop through and act on an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;names = hackers.each do |h|
  puts h[:name]}
end

# returns to the console:
# Matt
# Angie
# Joey
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;a href=""&gt;&lt;strong&gt;MAP or COLLECT&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The &lt;code&gt;.map&lt;/code&gt; aka &lt;code&gt;.collect&lt;/code&gt; enumerator allows us to do something to every element of an array or hash.&lt;br&gt;
It loops through and returns a new array based on some sort of condition or test.&lt;br&gt;
Every time it goes through iteration, it replaces the element that was there before with the new element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;uppercased_food = hackers.map do |h|
  h[:favorite_food].upcase
end

# returns ["TACOS", "CHOCOLATE", "BROCCOLI"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that &lt;code&gt;.map&lt;/code&gt;/&lt;code&gt;.collect&lt;/code&gt; doesn't change the original array, it creates a new one.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href=""&gt;&lt;strong&gt;FILTER, SELECT, or FIND_ALL&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When you want to access every element of an array, check if it matches some criteria, and return a new array of all the values that match.&lt;br&gt;
This won't let you perform any transformation of elements; it will only return the original elements based on whether a truthy or falsy value is returned from the block.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;juniors = hackers.filter do |h|
  h[:years_coding] &amp;lt; 8
end

# returns the "Joey" and "Matt" hashes in an array, 
# excluding the "Angie" hash
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;a href=""&gt;&lt;strong&gt;FIND&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;.find&lt;/code&gt; finds first element that matches a condition.&lt;br&gt;
This works just like FILTER, but only returns the first element that passes the condition or test.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ruby_pro = hackers.find do |h|
  h[:favorite_language] == "Ruby"
end

# returns the "Matt" hash
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that strings are case-sensitive. If &lt;code&gt;nil&lt;/code&gt; was returned for you here, you might have a typo.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href=""&gt;&lt;strong&gt;SUM&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;.sum&lt;/code&gt; allows us to find the total sum of an element in an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;total_years = hackers.sum {|h| h[:years_coding]}

# returns 19
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;a href=""&gt;&lt;strong&gt;SORT&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;.sort&lt;/code&gt; returns a new array where all the elements have been sorted based on some criteria. This will not alter the original array.&lt;br&gt;
Comparing elements in each iteration can be done using the &lt;a href=""&gt;'Spaceship Operator'&lt;/a&gt; &amp;lt;=&amp;gt;, aka the combined comparison operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;alphabetical = hackers.sort do |hacker1, hacker2|
  hacker1[:name] &amp;lt;=&amp;gt; hacker2[:name]
end

# returns an array in a new order, 
# starting with the "Angie" hash, followed by "Joey", 
# followed by "Matt"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are many, many more enumerators you can use, but the ones just mentioned will help you in most cases. Be sure to look through &lt;a href=""&gt;Ruby's documentation&lt;/a&gt; to learn more, and practice with them on your own to get used to how they work. Always keep in mind what your enumerator will return, and remember these handy tips:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When you want to manipulate elements in an array, use MAP&lt;/li&gt;
&lt;li&gt;When you want to query an array, use FIND or FILTER&lt;/li&gt;
&lt;li&gt;When you want to read things in an array, use EACH&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thanks for reading. Happy coding!&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>codenewbie</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Control Forms in React</title>
      <dc:creator>Matthew Kohn</dc:creator>
      <pubDate>Thu, 03 Mar 2022 21:51:55 +0000</pubDate>
      <link>https://dev.to/matthewkohn/control-forms-in-react-6p6</link>
      <guid>https://dev.to/matthewkohn/control-forms-in-react-6p6</guid>
      <description>&lt;p&gt;Control Forms in React is a tricky concept to learn, especially if you’re also learning about state, props, and hooks for the first time. This tutorial aims to illustrate how control forms work.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5e_q_pEP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/alpf0i9u9xpkgmc1tzwo.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5e_q_pEP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/alpf0i9u9xpkgmc1tzwo.jpg" alt="Handwritten form. Credit: https://www.shutterstock.com/image-photo/filling-form-business-credit-application-banking-67555918" width="390" height="280"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Uncontrolled Forms
&lt;/h2&gt;

&lt;p&gt;An &lt;strong&gt;&lt;em&gt;&lt;a href="https://reactjs.org/docs/uncontrolled-components.html"&gt;uncontrolled form&lt;/a&gt;&lt;/em&gt;&lt;/strong&gt; contains HTML form elements (input, select, etc.) where the user’s input lives in the DOM. With uncontrolled forms, you can “pull” this data from the DOM when the form is submitted, but there’s no way of knowing what the user types &lt;em&gt;as they type&lt;/em&gt; without a ton of explicit logic. &lt;br&gt;
There’s nothing wrong with this, it’s just a lot more work for you, the coder. Fortunately for us, there’s a cool way to control the data in our forms.&lt;/p&gt;
&lt;h2&gt;
  
  
  Control Forms
&lt;/h2&gt;

&lt;p&gt;React gives us the ability to keep track of the user’s input for dynamic use by storing data in something called state. By controlling the value of input fields of a form according to what a user types, this built-in React state is updated with every keystroke or click. A few examples of what this allows us to do might be to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Enforce input format, such as phone numbers or prices&lt;/li&gt;
&lt;li&gt;Conditionally disable buttons until certain fields are filled correctly&lt;/li&gt;
&lt;li&gt;Make inputs that seamlessly interact with other components&lt;/li&gt;
&lt;li&gt;Handle complex forms with multiple inputs for one piece of data, like an order form or newsletter signup.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  React’s useState Hook
&lt;/h2&gt;

&lt;p&gt;Before we get into how to make a control form, it’s important to understand what is meant by “state”. If you don’t already know how this works, I highly recommend reading &lt;a href="https://reactjs.org/docs/hooks-state.html"&gt;React’s docs on state&lt;/a&gt; and managing state in &lt;a href="https://beta.reactjs.org/learn/managing-state"&gt;React’s Beta docs&lt;/a&gt; before continuing.&lt;/p&gt;

&lt;p&gt;To summarize, &lt;strong&gt;&lt;em&gt;State&lt;/em&gt;&lt;/strong&gt; is data that is dynamic in your component. It changes over time as users interact with your application, and instead of being stored in the DOM it lives in React’s internal code. We can access state using the useState hook.&lt;/p&gt;

&lt;p&gt;All the state in your application is held in React’s internal code, not in the user’s browser. React has a useState function, or “hook”, that allows us to hook into React’s internal state inside of our function component. We’re going to use the useState hook to control our form.&lt;/p&gt;

&lt;p&gt;To change an uncontrolled form into a controlled form, we need to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Set up state&lt;/li&gt;
&lt;li&gt;Make the input values equal to the state variable&lt;/li&gt;
&lt;li&gt;Set this state in a callback function in the input’s event listener&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s see how to make this happen. If you’d like to follow along, make sure you have a code editor of your choice, such as &lt;a href="https://code.visualstudio.com/"&gt;VS Code&lt;/a&gt;. Also make sure you have &lt;a href="https://www.npmjs.com/"&gt;npm&lt;/a&gt; and Google Chrome installed, and &lt;a href="https://create-react-app.dev/"&gt;create a new React app&lt;/a&gt;. This might take a few minutes. &lt;/p&gt;

&lt;p&gt;In your terminal, start a new app with these steps:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app control-form-practice
cd control-form-practice
npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If all goes well, you should see the React logo rotating in your browser.&lt;/p&gt;

&lt;p&gt;Now, in your code editor, open the App.js file found in &lt;code&gt;control-form-practice/src/App.js&lt;/code&gt;. Replace everything in App.js with this starter JSX:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  return (
    &amp;lt;form style={formStyle()}&amp;gt;
      &amp;lt;label&amp;gt;Your Name:&amp;lt;/label&amp;gt;
      &amp;lt;input type="text" /&amp;gt;
      &amp;lt;label&amp;gt;Your Age:&amp;lt;/label&amp;gt;
      &amp;lt;select&amp;gt;
        &amp;lt;option value="youth"&amp;gt;0 - 17&amp;lt;/option&amp;gt;
        &amp;lt;option value="adult"&amp;gt;18 - 80&amp;lt;/option&amp;gt;
        &amp;lt;option value="elder"&amp;gt;80 +&amp;lt;/option&amp;gt;
      &amp;lt;/select&amp;gt;
      &amp;lt;label&amp;gt;
        If you love React, check this box =&amp;gt;
        &amp;lt;input type="checkbox" /&amp;gt;
      &amp;lt;/label&amp;gt;
      &amp;lt;label&amp;gt;Comments:&amp;lt;/label&amp;gt;
      &amp;lt;textarea /&amp;gt;
      &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}

export default App;

const formStyle = () =&amp;gt; {
  return { display:"flex", flexDirection:"column", margin:"40px auto", lineHeight: "50px", width: "400px", fontSize:"20px"  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(I've included a formStyle() function that's used for inline styling for readability purposes in your browser. There are much better ways to &lt;a href="https://styled-components.com/"&gt;style components&lt;/a&gt; FYI.)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---5XR-EUR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/auc5utcrs66kqok980la.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---5XR-EUR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/auc5utcrs66kqok980la.png" alt="A simple form in the browser" width="663" height="430"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Right now, this form is considered uncontrolled, and anything you type or select lives in your browser’s DOM.&lt;/p&gt;

&lt;p&gt;To make this a Control Form, we need to incorporate state into our input, select, and textarea tags. To start, we need to add state to our component.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Add State
&lt;/h2&gt;

&lt;p&gt;On line 1 in App.js, import the useState hook.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;import { useState } from 'react';&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then, inside the App component &amp;amp; before the return statement (line 4), let's declare our state variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [name, setName] = useState("");
const [age, setAge] = useState("young");
const [opinion, setOpinion] = useState("false");
const [comments, setComments] = useState("");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We've destructured the useState hook for each variable, each having its own state variable set to the initial value declared in useState(), and a setter function we'll use to update state every time the user interacts with the form.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Assign State
&lt;/h2&gt;

&lt;p&gt;Next, let's add state variables to our form elements. In these elements, add the 'value' attribute and assign their state variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input value={name} type="text" /&amp;gt;
...
&amp;lt;select value={age}&amp;gt;&amp;lt;/select&amp;gt;
...
&amp;lt;input value={opinion} type="checkbox" /&amp;gt;
...
&amp;lt;textarea value={comments} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point, if you try to interact with our form in your DOM you'll notice each field is frozen. If you look in your browser's console, you’ll see an error message:&lt;br&gt;
&lt;code&gt;Warning: You provided a 'value' prop to a form field without an 'onChange' handler...&lt;/code&gt;&lt;br&gt;
Have no fear. This is because we haven't added our setters to an event listener yet.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. Listen for State Changes
&lt;/h2&gt;

&lt;p&gt;Let's add event listeners to our form elements! The onChange event listener in React inputs expects a callback function, and has access to the event object, just like in vanilla JavaScript. &lt;/p&gt;

&lt;p&gt;We can use event.target.value for input, select, and textarea tags. Radio buttons and checkboxes are a little different, since they're triggered by a boolean value, and can be accessed with event.target.checked. Here's what that looks like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input onChange={(e) =&amp;gt; setName(e.target.value)} value={name} type="text" /&amp;gt;
...
&amp;lt;select onChange={(e) =&amp;gt; setAge(e.target.value)} value={age}&amp;gt;
...
&amp;lt;input onChange={(e) =&amp;gt; setOpinion(e.target.checked)} value={opinion} type="checkbox" /&amp;gt;
...
&amp;lt;textarea onChange={(e) =&amp;gt; setComments(e.target.value)} value={comments} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it! Now we have a simple &lt;a href="https://reactjs.org/docs/forms.html#controlled-components"&gt;control form&lt;/a&gt;. If you want to test out what we've done so far, inject our state variables into the JSX! Here's our final version of App.js, for your reference.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

function App() {
  const [name, setName] = useState("");
  const [age, setAge] = useState("young");
  const [opinion, setOpinion] = useState("false");
  const [comments, setComments] = useState("");

  return (
    &amp;lt;&amp;gt;
      &amp;lt;form style={formStyle()}&amp;gt;
        &amp;lt;label&amp;gt;Your Name:&amp;lt;/label&amp;gt;
        &amp;lt;input onChange={(e) =&amp;gt; setName(e.target.value)} value={name} type="text" /&amp;gt;
        &amp;lt;label&amp;gt;Your Age:&amp;lt;/label&amp;gt;
        &amp;lt;select onChange={(e) =&amp;gt; setAge(e.target.value)} value={age}&amp;gt;
          &amp;lt;option value="youth"&amp;gt;0 - 17&amp;lt;/option&amp;gt;
          &amp;lt;option value="adult"&amp;gt;18 - 80&amp;lt;/option&amp;gt;
          &amp;lt;option value="elder"&amp;gt;80 +&amp;lt;/option&amp;gt;
        &amp;lt;/select&amp;gt;
        &amp;lt;label&amp;gt;
          If you love React, check this box =&amp;gt;
          &amp;lt;input onChange={(e) =&amp;gt; setOpinion(e.target.checked)} value={opinion} type="checkbox" /&amp;gt;
        &amp;lt;/label&amp;gt;
        &amp;lt;label&amp;gt;Comments:&amp;lt;/label&amp;gt;
        &amp;lt;textarea onChange={(e) =&amp;gt; setComments(e.target.value)} value={comments} /&amp;gt;
        &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
      &amp;lt;h3&amp;gt;User Name: {name}&amp;lt;/h3&amp;gt;
      &amp;lt;h3&amp;gt;User Age: {age}&amp;lt;/h3&amp;gt;
      &amp;lt;h3&amp;gt;User Opinion: {opinion}&amp;lt;/h3&amp;gt;
      &amp;lt;h3&amp;gt;User Textarea: {comments}&amp;lt;/h3&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

export default App;

const formStyle = () =&amp;gt; {
  return { display:"flex", flexDirection:"column", margin:"40px auto", lineHeight: "50px", width: "400px", fontSize:"20px" }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>react</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Code Along with Fetch API</title>
      <dc:creator>Matthew Kohn</dc:creator>
      <pubDate>Mon, 15 Nov 2021 19:53:42 +0000</pubDate>
      <link>https://dev.to/matthewkohn/code-along-with-fetch-api-1h18</link>
      <guid>https://dev.to/matthewkohn/code-along-with-fetch-api-1h18</guid>
      <description>&lt;p&gt;The JavaScript built-in &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" rel="noopener noreferrer"&gt;Fetch API&lt;/a&gt; is awesome. It's a powerful, simple way to send requests and receive responses from a server or your local network. I like it because it's versatile and easy to use.&lt;/p&gt;

&lt;p&gt;Let's see &lt;strong&gt;how&lt;/strong&gt; it works by building a simple website. Today, we'll be using the &lt;a href="'https://dog.ceo/dog-api/'"&gt;Dog.ceo API&lt;/a&gt; to load random images of dogs in the &lt;a href="'https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction'"&gt;DOM&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Please Note&lt;/em&gt;: This tutorial is meant to introduce fellow Newbies looking to explore how the Fetch API works. There is a lot more to Fetch than what you'll read about here, and these examples are by no means exhaustive.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is an API?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.w3schools.com/js/js_api_intro.asp" rel="noopener noreferrer"&gt;API&lt;/a&gt; stands for &lt;strong&gt;A&lt;/strong&gt;pplication &lt;strong&gt;P&lt;/strong&gt;rogramming &lt;strong&gt;I&lt;/strong&gt;nterface. There are many different types of APIs that do many useful things for us. Here are a few examples of what they can do:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="'https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API"&gt;Browser APIs&lt;/a&gt; extend the functionality of your Browser (Chrome, Safari, Brave, etc) to help with visual &amp;amp; local interpretation of code (Client-Side).&lt;/li&gt;
&lt;li&gt;Server APIs extend the functionality of Web Servers, and can manage data for Client-Side requests around the world. &lt;/li&gt;
&lt;li&gt;Web APIs built into your Browser help with sending, receiving, and interpreting data from the Web (Server-Side), such as Third-Party APIs.&lt;/li&gt;
&lt;li&gt;Third-Party APIs allow you to download their code over the Web, once you know where &amp;amp; how to get it. Once you find one you like, &lt;a href="'https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs'"&gt;&lt;em&gt;read their Docs to learn more&lt;/em&gt;&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;APIs are particularly useful because they work &lt;a href="'https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing'"&gt;Asynchronously&lt;/a&gt;, meaning they don't run at the same time as other code so they don't hold anything important up, causing annoying delays in page loads or updates.&lt;/p&gt;

&lt;p&gt;The fetch() API is one flexible tool that will make your life as a Developer much easier. Fetch allows us to make general definitions for network request &amp;amp; response objects that you can manipulate how you see fit. You could use Fetch for a simple GET request to fetch information (like we are here), or you can include header and body information to make POST, PATCH, or DELETE requests to or from a database.&lt;/p&gt;

&lt;p&gt;At the end of the article I've included loads of links for further exploration down the rabbit hole of understanding how to use Fetch, Web APIs, and Asynchronous JavaScript.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8hfudbmn8yf63tptjm3y.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8hfudbmn8yf63tptjm3y.jpeg" alt="Dog catching ball at https://images.unsplash.com/photo-1620325698009-4163b8f6d501?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;amp;ixlib=rb-1.2.1&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;w=1170&amp;amp;q=80"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;h2&gt;
  
  
  Starter Code
&lt;/h2&gt;

&lt;p&gt;If you'd like to follow along, create an "index.html", a "style.css", and an "index.js" file in the text editor of your choice on the same folder-level. We'll be working in our "index.js" file for this example. &lt;br&gt;
Copy and paste this very generic starter HTML &amp;amp; CSS into their respective files. Or, create your own &amp;amp; have fun with it!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- ___index.html___ --&amp;gt;

&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;link rel="stylesheet" href="./style.css"&amp;gt;
    &amp;lt;title&amp;gt;Dog Pictures&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Dogs!&amp;lt;/h1&amp;gt;
    &amp;lt;script src="./index.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* ____style.css___ */

body {
  background-color: rebeccapurple; 
  padding-left: 30px; 
}
h1 {
  color: #fff;
}
img {
  max-width: 400px;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the bare-bones minimum of what you should start with. When we're done, play around with it and make it your own! What matters most is you start with at least a boilerplate HTML structure, and linking your "index.js" file in a &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag at the bottom of the &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When you open the HTML file in your Browser, it should look something like this:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzxq0nnobw9mcjg3jz86l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzxq0nnobw9mcjg3jz86l.png" alt="Starter Browser"&gt;&lt;/a&gt;&lt;br&gt;
We're going to be using your Browser's Developer Tools to view the data we're receiving from the Web Server. To open your Dev Tools, right-click your Browser and select &lt;em&gt;&lt;code&gt;Inspect&lt;/code&gt;&lt;/em&gt; to reveal the Dev Tools panel.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbszkmewft9ehkpj2gp35.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbszkmewft9ehkpj2gp35.png" alt="Selecting "&gt;&lt;/a&gt;&lt;br&gt;
Select the &lt;em&gt;"Console"&lt;/em&gt; tab to view your Console. You can leave this open for now.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffu1s3sp643gb11blim0s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffu1s3sp643gb11blim0s.png" alt="Dev Tools Console tab"&gt;&lt;/a&gt;&lt;br&gt;
Now it's time to write some JavaScript! Go to the blank "index.js" file in your Text Editor, and let's build our generic Fetch function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* ___index.js___ */

fetch(apiURL)                                 // Step 1
  .then(response =&amp;gt; response.json())          // Step 2
  .then(data =&amp;gt; console.log(data))            // Step 3
  .catch(error =&amp;gt; console.log(error));        // Step 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What is this function doing?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  STEP 1: FETCH REQUEST FROM AN API's URL
&lt;/h3&gt;

&lt;p&gt;"&lt;code&gt;fetch(apiURL)&lt;/code&gt;"&lt;br&gt;
The Fetch function is a built-in JavaScript function that makes an asynchronous &lt;a href="'https://javascript.info/promise-basics'"&gt;Promise&lt;/a&gt; to contact the apiURL we assign to the parameter. This Promise is just an assurance that Fetch will let us know once (or if) a response is received.&lt;/p&gt;

&lt;p&gt;Note that there is an option for a second parameter here that would contain metadata, such as the method, header, and body of the request. For a simple GET request like the one we're making, we can omit this and allow for Fetch's default parameters. Check out &lt;a href="'https://developer.mozilla.org/en-US/docs/Web/API/fetch'"&gt;MDN Web Docs information on Fetch syntax&lt;/a&gt; to learn more about making &lt;a href="'https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST'"&gt;POST&lt;/a&gt;, &lt;a href="'https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH'"&gt;PATCH&lt;/a&gt;, or &lt;a href="'https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE'"&gt;DELETE&lt;/a&gt; requests.&lt;/p&gt;
&lt;h3&gt;
  
  
  STEP 2: HANDLE THE RESPONSE
&lt;/h3&gt;

&lt;p&gt;"&lt;code&gt;.then(response =&amp;gt; response.json())&lt;/code&gt;"&lt;br&gt;
Once the Fetch's Promise has been kept, meaning the server has received the request, we chain a &lt;code&gt;.then()&lt;/code&gt; method to the Fetch Request to make another Promise. Any time a &lt;code&gt;.then()&lt;/code&gt; method is chained to a Promise, it won't start running until the previous Promise has completed.&lt;/p&gt;

&lt;p&gt;Inside this &lt;code&gt;.then()&lt;/code&gt;, we're going to make another Promise to take the response we're receiving, and tell the Fetch function to turn it into a JSON format that we can use.&lt;/p&gt;

&lt;p&gt;&lt;a href="'https://www.json.org/json-en.html'"&gt;JSON&lt;/a&gt; stands for "JavaScript Object Notation", and is a format commonly used to store data that can be accessed by any code language, not just JavaScript. JSON stores data in a long string, formatted with {}'s storing &lt;code&gt;key:value&lt;/code&gt; pairs inside []'s much like Objects and Arrays, but note that while JSON is similar to JavaScript, it is not JavaScript; it's just a long string. Once we receive our code in JSON format, we can get to the data we need and do things with it.&lt;/p&gt;
&lt;h3&gt;
  
  
  STEP 3: HANDLE THE DATA
&lt;/h3&gt;

&lt;p&gt;"&lt;code&gt;.then(data =&amp;gt; console.log(data))&lt;/code&gt;"&lt;br&gt;
Once Step 2's Response Promise has completed, we can now take the information the server sent to us, in JSON format, and do something with it by chaining another &lt;code&gt;.then()&lt;/code&gt; to &lt;code&gt;fetch()&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;The variable &lt;code&gt;data&lt;/code&gt; we're using here is actually the JSON object we got back from the server. You can name it anything you'd like and do what you want with it. For now, we will &lt;code&gt;console.log()&lt;/code&gt; the data we receive so we can look at this JSON object in our console. Once successful, we will be able to do whatever we want with that data, like pass it into a function.&lt;/p&gt;
&lt;h3&gt;
  
  
  STEP 4: HANDLE THE ERROR (if any)
&lt;/h3&gt;

&lt;p&gt;"&lt;code&gt;.catch(error =&amp;gt; console.log(error));&lt;/code&gt;"&lt;br&gt;
This is the end of the fetch() function. It's good practice to chain a &lt;code&gt;.catch()&lt;/code&gt; method to the Fetch function, in case there is a problem in any of the previous steps. This works like a &lt;code&gt;.then()&lt;/code&gt; method, but whenever a Promise rejects (fails), whatever happens inside the &lt;code&gt;.catch()&lt;/code&gt; will happen instead.&lt;/p&gt;

&lt;p&gt;Note that the Fetch Promise only rejects when a network error happens, not on HTTP errors. &lt;/p&gt;

&lt;p&gt;This would be a good place to send an error message to the console so the developer knows about it, or to display a message in the DOM so the User knows to try again later.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwtktq2soc53e0bhwzwne.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwtktq2soc53e0bhwzwne.jpeg" alt="Cute dog and ball"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;h2&gt;
  
  
  Our Request/Response Cycle
&lt;/h2&gt;

&lt;p&gt;Now that we have some background on how a Fetch Request works, let's make our Fetch function work!&lt;/p&gt;

&lt;p&gt;At the very top of your "index.js" file, above the fetch function, let's define the &lt;code&gt;apiURL&lt;/code&gt;. Add this line to your code:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const apiURL = 'https://dog.ceo/api/breeds/image/random';&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, refresh your Browser. The Response Object from the Fetch Request has been received, and if successful, our &lt;code&gt;fetch()&lt;/code&gt; function will now log that Object to your console. If the URL endpoint has a typo, the fetch() request will reject/fail, so make sure it's accurate.&lt;/p&gt;

&lt;p&gt;If you have a message in your Console that looks something like this, you're doing great:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foew7w4nk67azrf8afr7g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foew7w4nk67azrf8afr7g.png" alt="JSON response object"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice the value of "message" in this Response Object is a URL to a .jpg image. To narrow down to the specific information we want, let's change what we're logging to the Console in Step 3 from:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.then(data =&amp;gt; console.log(data))&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;to:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.then(data =&amp;gt; console.log(data.message))&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once you've done this, refresh your Browser and check out the Console again.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhj69covb5nsj7z27tjh9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhj69covb5nsj7z27tjh9.png" alt="A URL to an image"&gt;&lt;/a&gt;&lt;br&gt;
You should see just the random URL string we received in the Response Object from the Fetch Request in your Console, which is the value of &lt;code&gt;data.message&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now that we've singled out the data we want, we're ready to show that image in our DOM!&lt;/p&gt;

&lt;p&gt;First, let's make a function that takes a URL as a parameter, and uses that URL parameter to create an image we can display in our DOM.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function showImage(url) {
  const image = document.createElement('img');
  image.src = url;
  image.alt = 'Cute doggo';
  document.body.appendChild(image);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great, but now how do we use that function with our Fetch Request?&lt;/p&gt;

&lt;h3&gt;
  
  
  Pass &lt;code&gt;data.message&lt;/code&gt; to showImage()
&lt;/h3&gt;

&lt;p&gt;Go back to the &lt;code&gt;.then()&lt;/code&gt; line in STEP 3, and change:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.then(data =&amp;gt; console.log(data.message))&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;to:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.then(data =&amp;gt; showImage(data.message))&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, when you refresh your Browser, instead of logging data to your Console, you should see a picture of a cute dog in the DOM.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0xd60q2oa1jyw7exe2zf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0xd60q2oa1jyw7exe2zf.png" alt="DOM with an image of a dog"&gt;&lt;/a&gt;&lt;br&gt;
If a new random image of a dog appears in your DOM every time you reload the page, congratulations. You did it!&lt;/p&gt;

&lt;p&gt;Here's the final JavaScript for you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* ___index.js___ */

const apiURL = 'https://dog.ceo/api/breeds/image/random';

fetch(apiURL)
  .then(response =&amp;gt; response.json())
  .then(data =&amp;gt; showImage(data.message))
  .catch(error =&amp;gt; console.log(error));

function showImage(url) {
  const image = document.createElement('img');
  image.src = url;
  image.alt = 'Cute doggo';
  document.body.appendChild(image);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From here you could style the rest of your page, and continue to build this into any website of your imagining.&lt;/p&gt;

&lt;p&gt;Now that you know how to use Fetch API, you can use it to communicate with servers, create your own databases, or make a cool web app of your own design. &lt;/p&gt;

&lt;p&gt;Try exploring one of the many &lt;a href="'https://github.com/public-apis/public-apis'"&gt;free public Web APIs&lt;/a&gt; on your own to see what you can create by fetching what they have to offer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Continue Learning
&lt;/h2&gt;

&lt;p&gt;I also highly recommend looking further into why Fetch works on your own. Here are some of the sources I've learned from that helped me in my journey.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Event Loop:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="'https://www.youtube.com/watch?v=8aGhZQkoFbQ&amp;amp;t=476s'"&gt;"What the heck is the event loop anyway?" | Philip Roberts | JSConf EU&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop'"&gt;MDN Web Docs: "Concurrency Model and the Event Loop"&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Vital Acronyms:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="'https://en.wikipedia.org/wiki/Representational_state_transfer'"&gt;Wikipedia: "Representational State Transfer (REST)"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://en.wikipedia.org/wiki/Create,_read,_update_and_delete'"&gt;Wikipedia: "Create, Read, Update, and Delete (CRUD)"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://www.w3schools.com/xml/ajax_intro.asp'"&gt;w3schools: Asynchronous JavaScript and XML (AJAX)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://en.wikipedia.org/wiki/JSON'"&gt;Wikipedia: "JavaScript Object Notation (JSON)"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://developer.mozilla.org/en-US/docs/Web/HTTP'"&gt;MDN Web Docs: Hypertext Transfer Protocol (HTTP)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Tools and Resources:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="'https://jsonlint.com/'"&gt;JSONLint- The JSON Validator app&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en'"&gt;Google Chrome Web Store: JSON Formatter Extension&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://restfulapi.net/http-methods/'"&gt;REST API Tutorial: HTTP Methods&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  More about Fetch
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="'https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL'"&gt;MDN Web Docs: "What is a URL?"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview'"&gt;MDN Web Docs: "HTTP Overview"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'"&gt;MDN Web Docs: "Using Fetch"&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Thanks for reading, and happy coding!&lt;/em&gt;&lt;/p&gt;

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