<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: sheenasany</title>
    <description>The latest articles on Forem by sheenasany (@sheenasany).</description>
    <link>https://forem.com/sheenasany</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%2F890634%2Fb45e2fe8-e9e1-4b85-a077-351806d84603.JPG</url>
      <title>Forem: sheenasany</title>
      <link>https://forem.com/sheenasany</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/sheenasany"/>
    <language>en</language>
    <item>
      <title>How to use Mapbox using React-Map-Gl V7 for your React App for beginners</title>
      <dc:creator>sheenasany</dc:creator>
      <pubDate>Mon, 31 Oct 2022 00:08:43 +0000</pubDate>
      <link>https://forem.com/sheenasany/how-to-use-mapbox-using-react-map-gl-v7-for-your-react-app-for-beginners-2o10</link>
      <guid>https://forem.com/sheenasany/how-to-use-mapbox-using-react-map-gl-v7-for-your-react-app-for-beginners-2o10</guid>
      <description>&lt;p&gt;Mapbox is essentially a third-party JavaScript library that allows developers to build maps and display them in a web browser application. It's really great for users especially when maps include interactivity such as zooming in and out of a map, adding markers, and popups, and animated geographic data. Mapbox overall is super cool! However, it mostly works with Javascript. So how can we add this nifty tool to our React app? &lt;/p&gt;

&lt;p&gt;Along comes React-Map-Gl which was first created by Uber's Visualization team where they saw how powerful Mapbox could be and sought ways to implement it using React programming. Go &lt;a href="https://visgl.github.io/react-map-gl/docs" rel="noopener noreferrer"&gt;here&lt;/a&gt; for a deep dive into their Design Philosophy and Limitations. It's also open source so anyone is welcome to contribute to making it even better for future iterations. You can do so &lt;a href="https://visgl.github.io/react-map-gl/docs/contributing" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;When I first came across Mapbox to use in my Capstone project, I noticed that a lot of the current documentation, tutorials, and videos that existed were for React-Mapbox-Gl version 6.1 or 5.3. However, they've recently upgraded to v7.0 in Feb 2022 and changed MANY things behind the scenes so all the old tutorials out there needed some revamping and reconfiguring to get it to work with the newer version. I also noticed that there weren't a lot of new tutorials or videos incorporating v7.0 so I decided to start simple and write about how to create a map and add markers using this awesome API. For an in-depth look at the differences in versions, take a look &lt;a href="https://visgl.github.io/react-map-gl/docs/upgrade-guide" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Set-Up
&lt;/h1&gt;

&lt;p&gt;Now, to get started, download the package:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;npm&lt;/span&gt; &lt;span class="nx"&gt;install&lt;/span&gt; &lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="nx"&gt;save&lt;/span&gt; &lt;span class="nx"&gt;react&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nx"&gt;gl&lt;/span&gt; &lt;span class="nx"&gt;mapbox&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nx"&gt;gl&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;check that your dependencies look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;dependencies&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;^17.0.0&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;react-dom&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;^17.0.0&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;react-map-gl&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;^7.0.0&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;mapbox-gl&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;^2.0.0&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and import Map into your component along with Marker like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nb"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;Marker&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react-map-gl&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also, you'll need to import css styling as well so we can have the ability to set height and width to our map or to add additional styling to your map if you want to get fancy. But bear this in mind as we'll be needing this later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;mapbox-gl/dist/mapbox-gl.css&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In order to use Mapbox in our app, we'll need to &lt;a href="https://www.mapbox.com/" rel="noopener noreferrer"&gt;sign up&lt;/a&gt; with an account and enter some billing information. Even though it's free to use for developers, it's only free up to a certain point which is about 50,000 loads or so a month, and after that they'll charge a fee. Don't worry though because during development you should never come close to this number, but keep on eye on your dashboard as it will have a bar to let you know how many times your map has been mounted. For example, during pre and post development, I only had a total of 368 loads.    &lt;/p&gt;

&lt;p&gt;Once an account has been created, you'll want to create a token for your app. Nothing fancy needs to be added or modified to create that token, but make sure it's different from your default public token. You'll want to protect that token from the public which means we don't want to set it to a variable directly on our map component or anywhere in our app, but instead, make sure that it is set to &lt;code&gt;.env.local&lt;/code&gt; file in your react app. Make sure to check your &lt;code&gt;.gitignore&lt;/code&gt; file and that &lt;code&gt;.env.local&lt;/code&gt; comes with it. It usually does when you've used &lt;code&gt;create-react-app&lt;/code&gt;. Set &lt;code&gt;REACT_APP_MAPBOX_ACCESS_TOKEN&lt;/code&gt; as the variable name in this &lt;code&gt;.env.local&lt;/code&gt; file to your token.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;REACT_APP_MAPBOX_TOKEN&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;your token goes here&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The reason we do this is to prevent someone from taking our token and abusing it. We don't want anyone to take our token and go beyond that 50,000 loads. Not cool. Again, never commit your token in clear text anywhere in your app into Github... For more information on how to secure your Mapbox token, &lt;a href="https://visgl.github.io/react-map-gl/docs/get-started/tips-and-tricks#securing-mapbox-token" rel="noopener noreferrer"&gt;here's&lt;/a&gt; some more documentation on it as well as on the &lt;a href="https://visgl.github.io/react-map-gl/docs/get-started/mapbox-tokens" rel="noopener noreferrer"&gt;tokens&lt;/a&gt; themselves.&lt;/p&gt;

&lt;p&gt;You'll be calling this variable later so keep this in mind for now. That should be all the set-up we need for now. Let's get to coding.&lt;/p&gt;

&lt;h1&gt;
  
  
  Getting your map on the browser
&lt;/h1&gt;

&lt;p&gt;For our purposes here, we're going to start by simply showing the map and adding markers from our backend database.&lt;/p&gt;

&lt;p&gt;But first we want to set our initial viewport to where we want our app to load when first mounted on the browser. Let's make this controlled so we'll set state outside of the JSX like so.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;ReactMap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setViewState&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
        &lt;span class="na"&gt;latitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;39.8283&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;longitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;98.5795&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;zoom&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;3.5&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We no longer need to use width or height in this version within state so latitude, longitude, and zoom is all we need. We'll be setting that in styles in the JSX later. Here, the latitude and longitude is the center of the USA with a zoom of 3.5. The smaller the zoom number, the more zoomed out it will be, the higher the number, the more zoomed in it will be on those coordinates. &lt;/p&gt;

&lt;p&gt;Next, let's get into the return, call on &lt;code&gt;&amp;lt;Map&amp;gt;&lt;/code&gt;, and take all of our set up and write it up, like so.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt; &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;
      &lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;onMove&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;setViewState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;style&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;800&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;height&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;600&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;mapStyle&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"mapbox://styles/mapbox/streets-v9"&lt;/span&gt;
      &lt;span class="na"&gt;mapboxAccessToken&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;REACT_APP_MAPBOX_TOKEN&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we need to create a copy of our &lt;code&gt;viewState&lt;/code&gt; using the spread operator to grab that state we initialized it as. Next we include the &lt;code&gt;onMove&lt;/code&gt; callback whenever we want to manage the camera or view state for the map. This is triggered when the user moves the map around. Next is the styling of the map, how big we want the map to be on our page when it loads. Change specifications to your liking. &lt;/p&gt;

&lt;p&gt;Next we include the &lt;code&gt;mapStyle&lt;/code&gt; and add a styled map of our choosing from Mapbox. They have a gallery of already created map styles that you can use or gather inspiration from to create your own. Save one you created to your gallery, and grab the Style Url and plug it in. The one used above is a basic style. However, I actually am using one of the themed maps for my application, as you can see from the finished product.&lt;/p&gt;

&lt;p&gt;And finally, we call on our &lt;code&gt;REACT_APP_MAPBOX_TOKEN&lt;/code&gt; by setting it to &lt;br&gt;
&lt;code&gt;mapboxAccessToken&lt;/code&gt; so that your map from Mapbox is accessible. &lt;/p&gt;

&lt;p&gt;Your final code should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nb"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;Marker&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react-map-gl&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;mapbox-gl/dist/mapbox-gl.css&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;ReactMap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setViewState&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
        &lt;span class="na"&gt;latitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;39.8283&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;longitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;98.5795&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;zoom&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;3.5&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;
      &lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;onMove&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;setViewState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;style&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;800&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;height&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;600&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;mapStyle&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"mapbox://styles/mapbox/streets-v9"&lt;/span&gt;
      &lt;span class="na"&gt;mapboxAccessToken&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;REACT_APP_MAPBOX_TOKEN&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;ReactMap&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Now check your browser by running &lt;code&gt;npm start&lt;/code&gt; in your terminal.&lt;/p&gt;

&lt;h1&gt;
  
  
  Time to add some markers
&lt;/h1&gt;

&lt;p&gt;Now that our app is there, it's looking a little bland. Let's add some markers to it, shall we? &lt;/p&gt;

&lt;p&gt;In my app, I have data that I created on my backend using Ruby. However, knowing that Mapbox requires coordinates of latitude and longitude, I was able to include this in my seeds data to create the markers.&lt;/p&gt;

&lt;p&gt;You can decide to have your Markers controlled or uncontrolled, but in our case, let's keep things consistent and have app controlled.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;dataMarkers&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setDataMarkers&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;([])&lt;/span&gt;

    &lt;span class="nf"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;/markers&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;setDataMarkers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[]);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, I'm initializing the state of my Markers to an empty array so that when I fetch the data from my backend, it gathers the objects into an array and then I reset the state to my incoming data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;mapMarkers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;dataMarkers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;dataMarker&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Marker&lt;/span&gt; 
            &lt;span class="na"&gt;key&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;dataMarker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt; 
            &lt;span class="na"&gt;longitude&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;dataMarker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;longitude&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt; 
            &lt;span class="na"&gt;latitude&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;dataMarker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;latitude&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;img&lt;/span&gt; &lt;span class="na"&gt;src&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"/glowsticks.svg"&lt;/span&gt; &lt;span class="na"&gt;alt&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"Festival Icon"&lt;/span&gt;&lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
        &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nc"&gt;Marker&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we're creating a &lt;code&gt;mapMarkers&lt;/code&gt; function, taking our data that came through the get request, and mapping over each marker. After mapping over the data, we create each Marker with a key, a latitude, and a longitude that we have saved on our backend. We then will invoke  &lt;code&gt;mapMarkers&lt;/code&gt; within the JSX.&lt;/p&gt;

&lt;p&gt;I also created my own SVG of glowsticks for my festival map. If you want to use your own SVG, you can make one for free at Adobe or anywhere online. Once you've made one, save it to your public folder in your app and plug in the relative path. Don't forget to add alt text!&lt;/p&gt;

&lt;p&gt;Et viola! Restart your terminal and take a look at all your markers. &lt;/p&gt;

&lt;h1&gt;
  
  
  The final product
&lt;/h1&gt;

&lt;p&gt;Our final code should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nb"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;Marker&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react-map-gl&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;mapbox-gl/dist/mapbox-gl.css&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;ReactMap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setViewState&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
        &lt;span class="na"&gt;latitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;39.8283&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;longitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;98.5795&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;zoom&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;3.5&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;mapMarkers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;dataMarkers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;dataMarker&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Marker&lt;/span&gt; 
            &lt;span class="na"&gt;key&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;dataMarker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt; 
            &lt;span class="na"&gt;longitude&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;dataMarker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;longitude&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt; 
            &lt;span class="na"&gt;latitude&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;dataMarker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;latitude&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;img&lt;/span&gt; &lt;span class="na"&gt;src&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"/glowsticks.svg"&lt;/span&gt; &lt;span class="na"&gt;alt&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"Festival Icon"&lt;/span&gt;&lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
        &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nc"&gt;Marker&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;
      &lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;onMove&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;setViewState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;viewState&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;style&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="na"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;800&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;height&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;600&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
      &lt;span class="na"&gt;mapStyle&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"mapbox://styles/mapbox/streets-v9"&lt;/span&gt;
      &lt;span class="na"&gt;mapboxAccessToken&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;REACT_APP_MAPBOX_TOKEN&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nf"&gt;mapMarkers&lt;/span&gt;&lt;span class="p"&gt;()}&lt;/span&gt;
  &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;ReactMap&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And our outcome should look like this:&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%2Fi9vchlb8ucm7qx6bp5cv.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%2Fi9vchlb8ucm7qx6bp5cv.png" alt="Festival Map with markers"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I may create a series of these and have another post on adding popup functionality. Let me know your thoughts in the comments! &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>react</category>
    </item>
    <item>
      <title>Common Rookie Mistake: Mass Assignment Vulnerabilities</title>
      <dc:creator>sheenasany</dc:creator>
      <pubDate>Tue, 11 Oct 2022 04:47:28 +0000</pubDate>
      <link>https://forem.com/sheenasany/common-rookie-mistake-mass-assignment-vulnerabilities-4n04</link>
      <guid>https://forem.com/sheenasany/common-rookie-mistake-mass-assignment-vulnerabilities-4n04</guid>
      <description>&lt;p&gt;I know that there are many articles out there talking about mass assignment and how awesome it is, but for a new developer, we must also understand the dangers that this can bring to our database as it can open us up to vicious attacks. &lt;/p&gt;

&lt;p&gt;Even &lt;a href="https://github.blog/2012-03-04-public-key-security-vulnerability-and-mitigation/"&gt;Github&lt;/a&gt; in 2012 wasn't safe from this kind of attack when a user managed to find a crack in their security via a public update form and exploit it by adding their own file to Rails' github. How could this have happened?! These attacks are actually a bit more common than you think, especially in complex applications that involve customizable input values and perhaps programming errors that occur when data is needed to be stored rather quickly. Well, let's get to that and how to protect your database from attacks such as these.&lt;/p&gt;

&lt;p&gt;What exactly is mass assignment vulnerability? It's where a user is able to modify fields in your database which opens up for manipulation that was not intended on our part. Surprisingly, this happens in a lot of multiplayer video games because developers of these games, perhaps unbeknownst to them as to this particular vulnerability, are passing state data and storing it in their database, such as when not specifying the particular input from the form and their values as a single object rather than taking in whatever the user is inputting into the field. This case is unique to the front end and this &lt;a href="https://www.youtube.com/watch?v=r1j0COUMTqw"&gt;video&lt;/a&gt; is great at going into further detail regarding how to protect the front end as well, but let us turn our focus on how we can use Ruby on Rails to form that layer of protection..  &lt;/p&gt;

&lt;p&gt;Let's say we are a programmer creating the backend to allow our user to create a session upon signing up. You've created your form in the front end which can look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;form&lt;/span&gt; &lt;span class="na"&gt;onSubmit&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleForm&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    Enter your email address:
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;input&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"text"&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"user_email"&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    Enter a password:
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;input&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"password"&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"user_password"&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;password&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;input&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"submit"&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"Sign up"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;form&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the back end, we've got our corresponding controller handling when a new user is created:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;signup&lt;/span&gt;
  &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;User&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:user&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
  &lt;span class="c1"&gt;# =&amp;gt; User&amp;lt;email: "john@doe.com", password: "qwerty", is_admin: false&amp;gt;&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, our params are taking in three user values: an email, a password, and a boolean stating whether that user is an administrator or not. However, our front end is only allowing the user to enter their email and password. Then how can they possibly get to our database? Just because the input is not there to allow the user to change the is_admin status does not prevent them from creating an HTTP request with is_admin in the query string or request body. They perhaps may have been able to view the request body that displays all the detail of the user's account in their developer tools or was able to guess that the param existed with the correct key. Either way, a user can infiltrate by changing the values from false to true and allowing them access to admin level status to do some heavy damage, like being able to access other user accounts or adding value to their own account such as gems, money, or other items of note. &lt;/p&gt;

&lt;p&gt;Luckily for us, Rails has a wonderful way of raising an error if we do not protect the params on a controller when a user is created. So it will prompt us to declare which params to PERMIT upon creation. We do this by either explicitly assigning the params that we want to be taken into account within our form and only take in those params, or by white listing those specific params with a private method created within our controller. When white listing we are using what is called strong params. The use of the private method also allows the limitations of only using that method within that class which can provide a little bit more protection.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ruby"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;signup&lt;/span&gt;
  &lt;span class="c1"&gt;# Explicit assignment:&lt;/span&gt;

   &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;User&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="ss"&gt;email: &lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:email&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="ss"&gt;password: &lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="ss"&gt;:password&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="c1"&gt;# or whitelisting:&lt;/span&gt;

  &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;User&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;user_params&lt;/span&gt;
  &lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="kp"&gt;private&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;user_params&lt;/span&gt;
        &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;permit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="ss"&gt;:email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ss"&gt;:password&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;end&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In creating these strong params, if a user tries to include the is_admin key and attempt to infiltrate by changing the boolean to true when sending the HTTP request, the request will continue as normal, uninterrupted, but will limit the unpermitted params as it was not defined in our private user_params method. So long hackers! &lt;/p&gt;

&lt;p&gt;Resources: &lt;br&gt;
&lt;a href="https://ropesec.com/articles/mass-assignment/"&gt;ropsec&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>tutorial</category>
      <category>programming</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Fetch() vs Axios</title>
      <dc:creator>sheenasany</dc:creator>
      <pubDate>Fri, 16 Sep 2022 06:12:38 +0000</pubDate>
      <link>https://forem.com/sheenasany/fetch-vs-axios-185</link>
      <guid>https://forem.com/sheenasany/fetch-vs-axios-185</guid>
      <description>&lt;p&gt;I've previously written about doing simple fetch() requests in JS before. Moving into Ruby, I seemed to glaze past this fun way of creating a fetch request in much less code and in a shorter amount of time. Because what are programmers if not lazy, always searching for the next available hack to make typing faster, easier, and cleaner. &lt;/p&gt;

&lt;p&gt;Axios is a package that can be installed quite easily in any React Application with a simple &lt;code&gt;npm install axios&lt;/code&gt;, add the import on the component you choose to work on and viola! You have access to a promise based HTTP Client for your browser. &lt;/p&gt;

&lt;p&gt;Let's a look into the differences between the two starting with the basic syntax. First off, Axios needs fewer lines of code for a post request because it does away with the need to have a body property to send data to the endpoint where as Axios uses the data property. Another aspect that differs in syntax is the fact that Axios does not need the JSON.stringify method because it automatically converts data to JSON transforming the data returned from the server while only needing a simple header. With &lt;code&gt;fetch()&lt;/code&gt;, you have to parse out the data to a JS object by calling the &lt;code&gt;response.json&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const url = "http://url.com"
const data = { name: Tom, age: 20}

axios.post(url, data, { 
headers: {"Content-Type" :"application/json"} 
})
.then(res =&amp;gt; console.log(res.data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;VS&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const url = "http://url.com"
fetch(url, {
method: "POST"
headers: { "Content-Type" :"application/json"
},
body: JSON.stringify ({
name: "Tom",
age: "20"
})
})
.then(res =&amp;gt; res.json())
.then(data =&amp;gt; console.log(data))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another way that Axios differs is how you can override the default behavior that automatically happens when sending data back to the server previously mentioned. You can actually redefine the transformation that occurs, but with &lt;code&gt;fetch()&lt;/code&gt;, you'd have to do it manually. Let's see how this is done with a get request.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;axios.get("http://url.com")
.then(res =&amp;gt; console.log(res.data)
error =&amp;gt; {
console.log(error)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;vs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch("http://url.com")
.then(res =&amp;gt; res.json())
.then(data =&amp;gt; console.log(data))
.catch(error =&amp;gt; console.error(error))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Although you'd have one additional line of code with &lt;code&gt;fetch()&lt;/code&gt; it's kinda nice to not have to JSON-ify the data on a get request when Axios can do this for you. However, they can both fetch and parse the data the same way. &lt;/p&gt;

&lt;p&gt;Another interesting point of note is backward compatibility. Axios is quite popular in this aspect because it runs &lt;code&gt;XMLHttpRequest&lt;/code&gt; under the hood which makes it easier to run with little issue on a wide range of browsers, including older browsers like IE11. On the other hand &lt;code&gt;fetch()&lt;/code&gt; is currently only supported on current versions of Chrome, Firefox, Edge, and Safari which isn't to say that this long list isn't wide ranging either. However, you'd need to implement a polyfill for &lt;code&gt;fetch()&lt;/code&gt; which &lt;a href="https://blog.logrocket.com/axios-vs-fetch-best-http-requests/#:~:text=To%20send%20data%2C%20fetch(),a%20string%20using%20the%20JSON."&gt;this&lt;/a&gt; explains how to do, but can add additional steps to simply allow fetch to be accepted on older browsers whereas Axios can already do the work without the extra work. See? We are lazy..  &lt;/p&gt;

&lt;p&gt;The examples above implement the same functionality so deciding on which to use is personal preference and up to the developer as to what would work best for your project. There are many other really great examples as to how Axios makes life a little easier which can be read &lt;a href="https://blog.logrocket.com/axios-vs-fetch-best-http-requests/#:~:text=To%20send%20data%2C%20fetch(),a%20string%20using%20the%20JSON."&gt;here&lt;/a&gt; by Faraz Kelhini, especially when compared with &lt;code&gt;fetch()&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Resources: &lt;br&gt;
&lt;a href="https://axios-http.com/docs/intro"&gt;Axios Documentation&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>tutorial</category>
      <category>programming</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Abstracting Input Change Logic</title>
      <dc:creator>sheenasany</dc:creator>
      <pubDate>Fri, 26 Aug 2022 00:08:00 +0000</pubDate>
      <link>https://forem.com/sheenasany/abstracting-input-change-logic-3pcf</link>
      <guid>https://forem.com/sheenasany/abstracting-input-change-logic-3pcf</guid>
      <description>&lt;h2&gt;
  
  
  Cut down on Boilerplate Forms!
&lt;/h2&gt;

&lt;p&gt;As a budding programmer, we learn the easier routes of how to get things to work on React before stepping it up a notch and moving on to cleaner, drier, more concise code. Well, as a budding programmer you may be familiar with how to create a form using React by now, right? And I’m sure you’re well acquainted with how to set the state of each input value or how to create a function to capture all those input values in order to change the state, yes? And I’m sure you’re following best coding practices by keeping state and the function to handle that state in the same component. Or that you’re also setting the function to handle the onChange and Submit event outside of the JSX, correct? Or even that you're using controlled inputs on your form, right? Yes, I’m sure we’re all up to speed on that and that your code kinda looks like this then:&lt;/p&gt;

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



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

function Form() {

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [avatar, setAvatar] = useState("");
  const [mailingList, setMailingList] = useState(false);

  const handleUsername = (e) =&amp;gt; {
    setUsername(e.target.value)
  } 

  const handlePassword = (e) =&amp;gt; {
    setPassword(e.target.value)
  }

  const handleAvatar = (e) =&amp;gt; {
    setAvatar(e.target.value)
  } 

  const handleMailingList = (e) =&amp;gt; {
    setMailingList(e.target.checked)
  } 

  const handleSubmit = (event) =&amp;gt; {
    event.preventDefault();
    const formData = {
     username,
     password,
     avatar,
     accountType,
     newsletter
  }
  console.log(formData);
  }



  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;h1&amp;gt;Create an Account&amp;lt;/h1&amp;gt;
      &amp;lt;label htmlFor="username"&amp;gt;Username&amp;lt;/label&amp;gt;
      &amp;lt;input
        type="text"
        id="username"
        value={username}
        onChange={handleUsername}
      /&amp;gt;

      &amp;lt;label htmlFor="password"&amp;gt;Password&amp;lt;/label&amp;gt;
      &amp;lt;input
        type="password"
        id="password"
        value={password}
        onChange={handlePassword}
      /&amp;gt;

      &amp;lt;label htmlFor="avatar"&amp;gt;Avatar Image&amp;lt;/label&amp;gt;
      &amp;lt;input
        type="text"
        id="avatar"
        value={avatar}
        onChange={handleAvatar}
      /&amp;gt;
      &amp;lt;img src="https://i.pinimg.com/originals/0a/dd/87/0add874e1ea0676c4365b2dd7ddd32e3.jpg"
        alt="Avatar preview"
      /&amp;gt;

      &amp;lt;label&amp;gt;
        Join our Mailing List!
        &amp;lt;input
          type="checkbox"
          id="mailingList"
          checked={mailingList}
          onChange={handleMailingList}
        /&amp;gt;

      &amp;lt;/label&amp;gt;
      &amp;lt;input type="submit" value="Sign Up" /&amp;gt;
    &amp;lt;/form&amp;gt;

  )
}

export default Form
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Whew! What a beast... This is typical boiler plate, cut, copy, alt + click all those lines, and paste form essentially. But as a beginner, this is great to know! Get it down to the point where it's muscle memory. Then you're ready to move on to more dynamic forms that can adapt if you want to edit the form to capture more user data. Let's go into detail with this. &lt;/p&gt;

&lt;h2&gt;
  
  
  Set The State
&lt;/h2&gt;

&lt;p&gt;First start with the all those little slices of state for each input field. We're going to take all those states and mold them into one by initializing the state into an object with keys that each have an initial slice of state to them. Let's call that new slice of state &lt;code&gt;formData&lt;/code&gt; as it will be capturing all of our forms data. Like so: &lt;/p&gt;




&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FiMVJsoT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ay24axmvrp0cix956ucu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FiMVJsoT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ay24axmvrp0cix956ucu.png" alt="Difference between pre-boiler plate and condensing code into one slice of state" width="800" height="529"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;As you can see, we're taking all of those slices of state from the orange box, putting them under one slice of state in the yellow box, and initializing it as an object with key values set to the empty strings and false state for the mailing list as we had before when they were all sitting pretty in their own states. It's already starting to look a little less cluttered, huh? Let's move on. &lt;/p&gt;

&lt;p&gt;Next thing we need to do is look to our JSX where the values are set within each input. As you can see we previously set the value to the state we initially had, but now that we've condensed our state to &lt;code&gt;formData&lt;/code&gt;, let us now plug in that state and use dot notation to set our state the the key value of username. We'll need to plug this in for all of our values. &lt;/p&gt;




&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--CU6nmM_S--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/glnuxnmjafrc97rp8haa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CU6nmM_S--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/glnuxnmjafrc97rp8haa.png" alt="Highlighting the change of code in values" width="721" height="709"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;I'd like to point out here that the value for a checkbox is checked instead of value so keep that in mind as we move forward. &lt;/p&gt;

&lt;h2&gt;
  
  
  Deconstruct the Handler Functions
&lt;/h2&gt;

&lt;p&gt;Best practice dictates that we keep state and their function handlers wrapped in the same component so we are following that here. Next, let's hone our attention to the very same handler functions that we had for each of those slices of state set to capture the input values when the onChange event gets fired off every time a user submits a new value within that particular field. As you can see, they take up quite a bit of space as we're setting that state for EACH input field. Imagine if we had a much larger form taking in A LOT more information from the user. Our code would be a bit more exhaustive and repetitive. Let's fix that. &lt;/p&gt;

&lt;p&gt;First thing we're going to do is create a new function that will handle all the onChange events for each input field. We'll call it &lt;code&gt;handleChange&lt;/code&gt;. This next part gets a little tricky because our setter function, &lt;code&gt;setFormData&lt;/code&gt;, expects an object so we need to call it with an object. Therefore, we need to use curly braces when we invoke the setter function. What we want to do is have that object contain all of the data from the &lt;code&gt;formData&lt;/code&gt; variable so we'll be using the spread operator to copy all the original data from the formData variable, which, again, is all the data from the object. The second argument when using the spread operator is going to be the change that's occurring on that input field, the key of the input which is the targeted or updated change that's affecting the state. So here we're going to include &lt;code&gt;e.target.value&lt;/code&gt; as the value in the key value pair. &lt;/p&gt;




&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--igC68iNf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4qz06252icm5d93m3tj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--igC68iNf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4qz06252icm5d93m3tj.png" alt="Showing the difference between separate handlers for each state and condensing into one handler for formData state" width="694" height="640"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;This is already looking much nicer, but wait, this is only updating the username. What we need to do is update the other fields by finding a way to use the other keys in the object. We need a way to dynamically determine which part of the form we want to update. Luckily for us, the inputs actually have ids assigned to them that match exactly the name of the input fields we want to target, it matches the keys of our data object which is great for us! Maybe something to keep in mind when initially creating the form. It also does not necessarily mean you need to use id all the time, you can also use name if it has one or if you created one within each label. So here we go, let's use the ids for now.&lt;/p&gt;

&lt;p&gt;Let's create a variable in the new &lt;code&gt;handleChange&lt;/code&gt; function to specify each targeted field by id. This will target which key in state we want to update. If we want to use the variable key dynamically to determine which key in the form we're updating, we can write it by wrapping it in bracket notation and have the value of that key pair be the event grabbing the value on change. That will look like this: &lt;/p&gt;




&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mUYyOfIB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agcjapssb1bkg9e80hkw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mUYyOfIB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agcjapssb1bkg9e80hkw.png" alt="Creating a new variable to dynamically capture the key value pair and show where the code changes" width="504" height="220"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;However, there's one more thing that's not quite working anymore due to all our changes and it's the last field, our special checkbox. It needs particular logic in order to show true or false when checked or not instead of logging as just on. We can even test this using our Components extension in our DevTools by checking the true or false state we specified in our data object when we click the checkbox. But we still need to figure out some way of differentiating when we click on the check box that this kind of input is separate from all our other inputs. Let's add a new variable for that value so that every time the target event type is a checkbox, show checked, and if it's not a checkbox type, then return the other kinds of input values. This is where a ternary operator will come in handy to render this logic. &lt;/p&gt;




&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sZftgNnG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p32b0e8d7ryj0h0k6b9x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sZftgNnG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p32b0e8d7ryj0h0k6b9x.png" alt="Showing the change in code when adding the new variable of the logic needed to change state for checkbox" width="626" height="319"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Beautiful. Now the fun part. Delete all those old handlers. Clean house, my friend! And now, update all the old onChange handlers and replace them with the ONE &lt;code&gt;handleChange&lt;/code&gt; function we created. It will now be easier to add a new field if needed to our form by simply adding it to the data object and just including it in the JSX with the already created logic to render user changes. &lt;/p&gt;

&lt;h2&gt;
  
  
  Final Code
&lt;/h2&gt;






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

function Form() {

  const [formData, setFormData] = useState({
            username: "",
            password: "",
            avatar: "",
            mailingList: false
  })

    function handleChange(event) {
        const key = event.target.id
        const value = event.target.type === "checkbox" 
        ? event.target.checked : event.target.value

        setFormData({ 
          ...formData, 
          [key]: value
        })
      } 

  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;h1&amp;gt;Create an Account&amp;lt;/h1&amp;gt;
      &amp;lt;label htmlFor="username"&amp;gt;Username&amp;lt;/label&amp;gt;
      &amp;lt;input
        type="text"
        id="username"
        value={formData.username}
        onChange={handleChange}
      /&amp;gt;

      &amp;lt;label htmlFor="password"&amp;gt;Password&amp;lt;/label&amp;gt;
      &amp;lt;input
        type="password"
        id="password"
        value={formData.password}
        onChange={handleChange}
      /&amp;gt;

      &amp;lt;label htmlFor="avatar"&amp;gt;Avatar Image&amp;lt;/label&amp;gt;
      &amp;lt;input
        type="text"
        id="avatar"
        value={formData.avatar}
        onChange={handleChange}
      /&amp;gt;
      &amp;lt;img src="https://i.pinimg.com/originals/0a/dd/87/0add874e1ea0676c4365b2dd7ddd32e3.jpg"
        alt="Avatar preview"
      /&amp;gt;

      &amp;lt;label&amp;gt;
        Join our Mailing List!
        &amp;lt;input
          type="checkbox"
          id="mailingList"
          checked={formData.mailingList}
          onChange={handleChange}
        /&amp;gt;

      &amp;lt;/label&amp;gt;
      &amp;lt;input type="submit" value="Sign Up" /&amp;gt;
    &amp;lt;/form&amp;gt;

  )
}

export default Form
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;So succinct, no? &lt;/p&gt;

&lt;h2&gt;
  
  
  Bonus: Adding a Post Request
&lt;/h2&gt;

&lt;p&gt;With every proper form, we would want to capture and store new user data somewhere, right? Well, we have our form ready to accept a POST request to it. We just need to add it to the &lt;code&gt;handleForm&lt;/code&gt; function so that any new user input gets captured and added to our database. Here's a simple example:&lt;/p&gt;






&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleForm = (e) =&amp;gt; {
    e.preventDefault()

      fetch("http://localhost:3000", {
        method: "POST",
        headers: {
          "Content-Type" : "application/json"
         },
        body: JSON.stringify(formData)
        })
         .then(res =&amp;gt; res.json())
         .then(data =&amp;gt; setNewFormData(data))

      setFormData({
            username: "",
             password: "",
            avatar: "",
            mailingList: false
      })
    } 
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;The second promise will include the function that will handle the new state taking in the new data that we're adding to the database. That will be up to you to decide where you want that function to live and whether you'll need to pass it down as a prop to your form component, but for now, this is the boilerplate POST request you can add on to your form. &lt;/p&gt;

&lt;p&gt;If you notice that the input fields aren't resetting once you submit new data, then look to reset the state back to initial object state that holds the empty strings and false value once the request has been completed. &lt;/p&gt;

&lt;p&gt;Now go out there and make magic happen by trying it out yourself! ✨&lt;/p&gt;

&lt;p&gt;Resources:&lt;br&gt;
&lt;a href="https://scrimba.com/scrim/co2a44c6a936050a5ec381235?pl=pBQgdHZ"&gt;Visual Representation&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>beginners</category>
      <category>tutorial</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Listen Up! To Clicks and Submit</title>
      <dc:creator>sheenasany</dc:creator>
      <pubDate>Wed, 03 Aug 2022 01:55:00 +0000</pubDate>
      <link>https://forem.com/sheenasany/listen-up-to-clicks-and-submit-50hc</link>
      <guid>https://forem.com/sheenasany/listen-up-to-clicks-and-submit-50hc</guid>
      <description>&lt;h1&gt;
  
  
  Common Event Listeners in JavaScript
&lt;/h1&gt;

&lt;p&gt;Are you in a coding bootcamp? Do you barely understand how an event listener works or even how to create one? I've got two that'll be incredibly useful for you when you're first starting off on your coding journey. But first, let's explain what these event listeners are in vanilla Javascript. &lt;/p&gt;

&lt;h3&gt;
  
  
  The Basics
&lt;/h3&gt;

&lt;p&gt;Event listeners are used for when an event happens and you want something to be done, such as when a user &lt;em&gt;clicks&lt;/em&gt; a button or they &lt;em&gt;submit&lt;/em&gt;  information within a form. Essentially when these events are triggered it allows for interesting changes that affect the outcome of the interaction. This, I find, to be one of the most exciting things to code. It's the every day clicks and that we use when resizing a window or scrolling down a webpage or having our mouse hover over an image, text, or link. The possibility of creating code that enhances user interaction is endless. In this particular case we will focus on Javascript DOM Event Listeners, specifically the &lt;b&gt;click&lt;/b&gt; and &lt;b&gt;submit&lt;/b&gt; events. These two listeners combined can create really dynamic pages on your first few days of coding and give an instant feeling of satisfaction when they actually work. &lt;/p&gt;

&lt;h3&gt;Click Event Syntax&lt;/h3&gt; 

&lt;p&gt;When using a click event we first need to create or grab an element in order to add the event listener to it. Since this is a click event, you want to state the event within the parameters along with a function. Here's an example: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;element.addEventListener('click', function ());&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We can keep this function anonymous or we can have a callback function within the parameters so that you can create a separate function for that specific event listener and declare all the things you want to happen for that particular event. But for now, let's console log that click to see if you targeted the correct element!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;element.addEventListener('click', () =&amp;gt; {
    console.log('Hello New World!');
}

//=&amp;gt; 'Hello New World!'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see that when you click on that particular element, whether it be a button, an image, or an h1 title tag, "Hello New World" should appear in the console as many times as you've clicked that element. Cool, huh? &lt;/p&gt;

&lt;p&gt;Another fun way to test a click event is by using alert instead of console log. This will create a pop up alert of whatever text you want to appear upon the click. This can be very handy if you just want to create an alert for any particular user interaction, but it can also put a little excitement when testing out your click events.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;element.addEventListener('click', () =&amp;gt; {
    alert("Well, hello world!"); 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt; Submit Event Syntax&lt;/h3&gt;

&lt;p&gt;Now, submit events are a little different. If the HTML is formatted well, you'll want to grab the whole form, and NOT the button that appears with the form. The submit event is listening for input submission within the form and not a click event. Here's an example of what that looks like: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;element.addEventListener('submit', function())&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Of course, console log, console log, console log! However, this console log will be a little different as, again, it won't be listening for a click event for a submit event. The 'e' here stands for event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;element.addEventListener('submit', (e) =&amp;gt; {
    console.log(e.target.value ) 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Wait a second... nothing happened when I tried to submit something! Here's the thing, the page, on a submit, will refresh automatically so it basically wipes your input and you never get to see it after the first submit click. To prevent this from happening, we would include .preventDefault() on the event. Like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;element.addEventListener('submit', (e) =&amp;gt; {
    e.preventDefault() 
        console.log(e.target.value ) 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;e.target.value&lt;/code&gt; basically means that on the event, target the value within the input submission box and console log that back to me. You should see whatever you entered in the input in your console log. &lt;/p&gt;

&lt;p&gt;And there ya have it! Now go out there and play around with these fun event listeners! &lt;/p&gt;

&lt;p&gt;Resources: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.w3schools.com/js/js_htmldom_eventlistener.asp"&gt;JavaScript DOM EventListener&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>tutorial</category>
      <category>codenewbie</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Demystifying Fetch()</title>
      <dc:creator>sheenasany</dc:creator>
      <pubDate>Tue, 12 Jul 2022 04:46:04 +0000</pubDate>
      <link>https://forem.com/sheenasany/demystifying-fetch-5gjc</link>
      <guid>https://forem.com/sheenasany/demystifying-fetch-5gjc</guid>
      <description>&lt;p&gt;I have to admit, fetch was (and still is at times) the most difficult concept for me to wrap my head around. I've been reading countless articles, trusted and some not so trusted, watching tons of YouTube videos and speaking to many of my colleagues  and instructors who have been attempting to help me demystify it in my brain. Why isn't my data parsing correctly? Why does my second promise come up with an error? Why does an error show when I use &lt;code&gt;.forEach?&lt;/code&gt; Why is nothing showing on my webpage?! Why isn't this thing FETCHING?!&lt;/p&gt;

&lt;p&gt;I understand your frustration. So I am going to attempt to break it down for those who are also having a difficult time grasping the most essential piece of code you need to understand in order to get anything working on your webpage.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;A Little Background&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The Fetch API can be used to get data from a local or remote file or a database from an API, or we can use it to push new data to a database in an API. It's similar to the &lt;code&gt;XMLHttpRequest&lt;/code&gt; but fetch is most commonly used as a preferred method to access data because it's promise based, it works asynchronously to promise data and return the data when the page is fully loaded. There are a lot of other reasons why fetch is better than &lt;code&gt;XMLHttpRequest&lt;/code&gt;, but you don't need to know that now. Let's just focus on the basic stuff.&lt;/p&gt;

&lt;p&gt;I know this already seems like a bit much, but if you don't know about asynchronous JavaScript, I suggest you take some time to watch this &lt;a href="https://vimeo.com/549507533?embedded=true&amp;amp;source=vimeo_logo&amp;amp;owner=106070186"&gt;video&lt;/a&gt;. It gives a great simplified explanation of what I mean when I say asynchronous JavaScript and touches on fetch as well. The more information, the better, right?&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Syntax&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The fetch command is usually one of the first lines of code you need in order to access your data so that you actually see and interact with that data on a webpage as a client or user. First things first though, you need the data. Where would one get data? Well, we're starting simple, so let's just say that we have data that's all ready to be used in whatever code editor you use. You can access that file locally as db.json(or whatever you want to call that JSON file).  This would be the easiest way. That file could look something like this and should be in JSON syntax.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
{
    "name": "John",
     "age": 22,
    "gender": "male",
},
{
    "name": "Susie",
    "age": "20",
     "gender": "female"
}
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For more information on JSON take a look &lt;a href="https://www.programiz.com/javascript/json"&gt;here&lt;/a&gt; for a simplified explanation with some examples.  On to the next!&lt;/p&gt;

&lt;p&gt;Now, you've got your file and you're ready to start accessing this data and plugging it in on the interweb. How would you do that? Well, with fetch! We're gonna tell JavaScript to go and &lt;strong&gt;&lt;em&gt;"fetch"&lt;/em&gt;&lt;/strong&gt; our stuff that we want to use. We'll do so with this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;fetch()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Within the parentheses, or the parameters, we would put in the file or the URL of the server where our data currently lives. In this case, we're just going to fetch the JSON file. Don't forget to include quotation marks, doesn't matter if they're double or single, as that file or URL needs to be a string. I know it's silly to mention, but it's those little mistakes that tend to have you pulling out your hair when you're trying to get your code to work so just keep it in the back of your mind. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;fetch('dummy.json')&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is also called a GET request. You don't need any other configuration in order to make this a GET request. See? Simple! You can also use POST, PATCH, or DELETE with some configuration with this first line, but let's just focus on our GET request for now.&lt;/p&gt;

&lt;p&gt;Well, we fetched our data, now what do we do? We're now going to request a response by chaining a method onto fetch called &lt;code&gt;.then&lt;/code&gt;. You can also do this with async/await, but we're only focusing on the .then method.&lt;/p&gt;

&lt;p&gt;With the &lt;code&gt;.then()&lt;/code&gt; we're going to request a response from the server to parse our stream of data and send us something in return while we wait. We know that our data is JSON so let's use another simplified method (&lt;a href="https://www.programiz.com/javascript/arrow-function"&gt;arrow function&lt;/a&gt;) to get that response and use the .json() method to return a promise for us. We have to return the data from the callback function in order to use the data in the next &lt;code&gt;.then()&lt;/code&gt; method call.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('dummy.json')`
.then(response =&amp;gt; response.json())`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Don’t forget to console log to make sure your data is being captured with this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.then(response =&amp;gt; console.log(response))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember to add the &lt;code&gt;.json()&lt;/code&gt; as just console logging it isn't really doing anything with the data yet. We still need it to be in object format so remove the console.log after you've confirmed it works.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Pizza Analogy&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Okay, so now that we're politely telling JavaScript to give us a response it's going to take some time doing so, but luckily for us, it's asynchronous which means it will run all our other lines of codes first and then come in when it's ready with our data. Remember when I mentioned that fetch is actually "promised based"? Well let me explain that a little further here. &lt;/p&gt;

&lt;p&gt;I heard an amazing analogy from a video I watched during my course that I hope provides a better understanding of how fetch works. Imagine that you're ordering pizza from your favorite pizza place. You order from your phone, and that order (fetch request) gets sent to the pizza company (the server) who then send you a receipt (the response/promise) of when your order will arrive. But it takes some time for that pizza to get to you as it needs to be driven and delivered to you. You don't sit there and watch the clock, you're more than likely watching tv and doing other things while you wait for your pizza (asynchronous JS). When your pizza arrives it comes in a box (.json) that then needs to be opened in order for you to eat it. &lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The Final Act&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Alright, this next part gets a little tricky. So the data is being fetched and we're requesting promises for the data to be sent back to us when the data is ready. But we want to do something with that data once it's been translated for us. That's where the second promise comes in, another .then(). This .then is the one that does all the heavy lifting. But first! Console log it! Like so:&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;From here you can then customize how you want the data to be retrieved and how it sums up on the page, whether you're iterating over an array of data from your JSON file, or from an external API, creating new elements to append images to, or creating event listeners to enhance user interaction on your app or webpage. Hopefully, this understanding will help you get started. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources:&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"&gt;Using Fetch API&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.programiz.com/javascript/json"&gt;JSON&lt;/a&gt;&lt;br&gt;
&lt;a href="https://vimeo.com/551936657?embedded=true&amp;amp;source=vimeo_logo&amp;amp;owner=106070186"&gt;GET Requests&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.youtube.com/watch?v=djCuFrLLjVk"&gt;Working With Data &amp;amp; APIs in JavaScript&lt;/a&gt;&lt;/p&gt;

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