<?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: Chris</title>
    <description>The latest articles on DEV Community by Chris (@chris10garcia).</description>
    <link>https://dev.to/chris10garcia</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%2F1044601%2Ff29e952e-61fe-4f88-9a49-f93ac88f0046.jpeg</url>
      <title>DEV Community: Chris</title>
      <link>https://dev.to/chris10garcia</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/chris10garcia"/>
    <language>en</language>
    <item>
      <title>Using socketio in a full stack application</title>
      <dc:creator>Chris</dc:creator>
      <pubDate>Sun, 10 Mar 2024 21:49:29 +0000</pubDate>
      <link>https://dev.to/chris10garcia/using-socketio-in-a-full-stack-application-4pd6</link>
      <guid>https://dev.to/chris10garcia/using-socketio-in-a-full-stack-application-4pd6</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;&lt;code&gt;socketio&lt;/code&gt; is an event driven library that allows for real-time, bi-directional communication between server and client. It is mostly used for chat applications but for my project, I used it to replace the HTTP server client communication.&lt;/p&gt;

&lt;p&gt;For my phase 5 project blog, I decided to share how to implement &lt;code&gt;socketio&lt;/code&gt; with my &lt;a href="https://github.com/Chris10Garcia/phase-4-final-project-crossfit-workout-planner"&gt;full stack application&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;My goal with using &lt;code&gt;socketio&lt;/code&gt; was to replace the communication between the frontend and backend but keep as much of my project logic intact and the same. This means replacing all fetch requests (GET, POST, PATCH, and DELETE) and API routes  but still keep how my project processes that data on the frontend and backend.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up &lt;code&gt;socketio&lt;/code&gt;
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Backend
&lt;/h3&gt;

&lt;p&gt;Flask was a requirement for my phase 5 project so I used the  'flask-socketio' package. I am using a python virtual shell to install my packages, so I ran the following command in terminal: &lt;code&gt;pyenv install flask-socketio&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;On the server side, you instantiate your flask app and configure it as you normally do, but with &lt;code&gt;flask-socketio&lt;/code&gt; you need to do the following additional things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You need to edit your CORS and set &lt;code&gt;resources={r"/*":{"origins":"*"}}&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;You need to insatiate a &lt;code&gt;socketio&lt;/code&gt; object, pass your app into it, and set the CORS settings&lt;/li&gt;
&lt;li&gt;Instead of running &lt;code&gt;app.run(port=5555, debug=True)&lt;/code&gt; you instead run &lt;code&gt;socketio.run(app, debug=True, port=5555)&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# config file
from flask import Flask
from flask_socketio import SocketIO
from flask_cors import CORS


# Instantiate app
app = Flask(__name__)

# Instantiate CORS
CORS(app, resources={r"/*":{"origins":"*"}})

socketio = SocketIO(app, cors_allowed_origins="*")


# app file
if __name__ == '__main__':
    socketio.run(app, debug=True, port=5555)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you have a &lt;code&gt;socketio&lt;/code&gt; server running on the backend&lt;/p&gt;

&lt;h3&gt;
  
  
  Frontend
&lt;/h3&gt;

&lt;p&gt;Let’s set up the frontend. Install the package, &lt;code&gt;npm install socket.io-client&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now to establish your frontend connection, you instantiate a &lt;code&gt;socketio&lt;/code&gt; object&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const socket = io("localhost:5555", {
transports: ["websocket"],
            cors: { origin: "*",},
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are some settings to pass:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first is the domain to connect to. We're passing our local host backend address here &lt;/li&gt;
&lt;li&gt;Second, we're passing a dictionary of settings&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;socketio&lt;/code&gt; uses both websockets and http connections, where the latter is a backup. to ensure my project uses websockets, I configured it to only establish that connection. this is optional / dependent on what your project goals are&lt;/li&gt;
&lt;li&gt;cors: setting the cors settings&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note that with each instance of the socket object, a new connection is established. I wanted to have one connection so I created this socket in the &lt;code&gt;App&lt;/code&gt; component as a global variable. I then used React context to pass this object directly to child components that receive and send data.&lt;/p&gt;

&lt;p&gt;Start your react app and the &lt;code&gt;socketio&lt;/code&gt; connection is now establish.&lt;/p&gt;

&lt;h3&gt;
  
  
  Testing Your Connection
&lt;/h3&gt;

&lt;p&gt;To ensure and test that your connection works, lets include the following&lt;/p&gt;

&lt;p&gt;On the backend &lt;code&gt;app.py&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@socketio.on("connect")
def handle_connect():
    print("Client connected!")
    emit( "connected", {"data": f"id: {request.sid} is connected"})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;socketio&lt;/code&gt; for python and flask uses decorators to register events.&lt;/p&gt;

&lt;p&gt;One special event is called "connect". Calling &lt;code&gt;socketio.on("connect")&lt;/code&gt; event decorator wrapped around a function will call that function every time a first connection is established.&lt;/p&gt;

&lt;p&gt;Here, every time we connect on the backend, we print out to the terminal "client connected".&lt;/p&gt;

&lt;p&gt;Next we &lt;code&gt;emit&lt;/code&gt; data back. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;emit&lt;/code&gt; is a &lt;code&gt;socketio&lt;/code&gt; function that sends data to the name of the room you are sending that data to. The next argument is the data you're sending. &lt;code&gt;socketio&lt;/code&gt; JSONIFY your data automatically so you do not need to use that function. &lt;/p&gt;

&lt;p&gt;So here, we are sending data to the frontend to a room called "connected". Please note, do not use special key word events such as connect or disconnect as it will cause bugs to occur.&lt;/p&gt;

&lt;p&gt;On the frontend,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    socket.on("connected", (data)=&amp;gt;{
        console.log(data)
      })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;socket.on&lt;/code&gt; is similar to the backend where the first argument is the name of the room. However, this uses a second argument as a callback function, where the data is passed and you can perform whichever action you want. In our case, we receive the socket id and it gets printed out in the console log. This will indicate to us that the connection was successfully established&lt;/p&gt;

&lt;h1&gt;
  
  
  Converting my application
&lt;/h1&gt;

&lt;p&gt;In the &lt;code&gt;App&lt;/code&gt; component, a fetch get request is performed within the &lt;code&gt;useEffect&lt;/code&gt; hook to get the data from the backend. I replaced these fetch requests as follows:&lt;/p&gt;

&lt;p&gt;original:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; fetch("/workout_plans")
      .then( r =&amp;gt; r.json())
      .then( d =&amp;gt; setPlans(d))

    fetch("/schedules")
      .then( r =&amp;gt; r.json())
      .then( d =&amp;gt; setSchClasses(d))

    fetch("/coaches")
      .then( r =&amp;gt; r.json())
      .then( d =&amp;gt; setCoaches(d))

    fetch("/exercise_moves")
      .then( r =&amp;gt; r.json())
      .then( d =&amp;gt; setMoves(d))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to: &lt;br&gt;
    socket.on("coaches",  data =&amp;gt; setCoaches(data))&lt;br&gt;
    socket.on("schedules",  data =&amp;gt; setSchClasses(data))&lt;br&gt;
    socket.on("workout_plans",  data =&amp;gt; setPlans(data))&lt;br&gt;
    socket.on("exercise_moves",  data =&amp;gt; setMoves(data))&lt;/p&gt;

&lt;p&gt;&lt;code&gt;socketio&lt;/code&gt; is listening to these four rooms for data.&lt;/p&gt;

&lt;p&gt;On the backend. I created a function that pulls all of my data from the database. Note, the objects from my DB needs to be serialized. I used &lt;code&gt;flask-marshamallow&lt;/code&gt; and &lt;code&gt;marshamallow&lt;/code&gt; to serialize these DB objects and include or exclude specific relationships and fields. if your data from the backend doesn't have complex relationships that require some type of serialization, you may pass them directly into &lt;code&gt;socketio&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The data is then emitted to the rooms I specified:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def refresh_all_data():
    coaches = Coach.query.all()
    workout_plans = Workout_Plan.query.all()
    exercise_moves = Exercise_Move.query.all()
    schedules = Schedule.query.all()

    emit("coaches", coaches_schema.dump(coaches))
    emit("workout_plans", workout_plans_schema.dump(workout_plans))
    emit("exercise_moves", exercise_moves_schema.dump(exercise_moves))
    emit("schedules", schedules_schema.dump(schedules))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thus, when the frontend and backend first connect, within the on "connect" event, I call on this &lt;code&gt;refresh_all_data()&lt;/code&gt; function. All of the records are pulled, the data is serialized, and it is then emitted to these rooms.&lt;/p&gt;

&lt;p&gt;On the frontend, these rooms are being listened to, and when the data is received, the object data is passed to the state variables established, updating the frontend's various views. Since these rooms are within the &lt;code&gt;useEffect&lt;/code&gt; hook, React re-renders again but not infinitely. Everything else in the &lt;code&gt;App&lt;/code&gt; component stays the same.&lt;/p&gt;

&lt;p&gt;Next, all components with the suffix &lt;code&gt;Form&lt;/code&gt; utilize fetch requests for patching, or posting data. Also within the &lt;code&gt;ClassScheduleDetail&lt;/code&gt; component, there are fetching delete requests. These components logic are dependent on acknowledgements, and &lt;code&gt;socketio&lt;/code&gt; allows you to provide this when data is emitted and received.&lt;/p&gt;

&lt;p&gt;Utilizing &lt;code&gt;CoachForm&lt;/code&gt; as an example, previously when a form data is submitted, there were two routes: if the form was submitting a new object or updating an existing object. Within each of those two routes, if the response was ok, to perform various actions involving refreshing the component and setting the page to show the object or to display the error from the backend as to why it didn't work.&lt;/p&gt;

&lt;p&gt;Previously:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  function submitData(values){

    if (values.id === ""){
      fetch("/coaches", {
        method: "POST",
        headers: {"Content-Type" : "application/json"},
        body: JSON.stringify(values)
      })
      .then( r =&amp;gt; {
        if (r.ok){
          r.json().then(data =&amp;gt; {
            setRefresh(!refresh)
            history.push(`/coaches/${data.id}`)
            setFormData(data)
            setApiError({})
          })
        } else {
          r.json().then( err =&amp;gt; {
            setApiError(err)
          })
        }
      })
    } else {
      fetch(`${values.id}`, {
        method : "PATCH",
        headers : { "Content-Type" : "application/json"},
        body : JSON.stringify(values)
      })
      .then( r =&amp;gt; {
        if (r.ok){
          r.json().then(data =&amp;gt; {
            setRefresh(!refresh)
            setApiError({})
          })
        } else {
          r.json().then(err =&amp;gt; {
            setApiError(err)})
        }
      })
    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All of my components that processed data like this all follow a very similar logic pattern. I replaced these fetch requests with the following on the frontend:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function submitData(values){

    if (values.id === ""){
      socket.emit("new_coach", values, result =&amp;gt; {
        if (result.ok){
          setRefresh(!refresh)
          history.push(`/coaches/${result.data.id}`)
          setFormData(result.data)
          setApiError({})
        } else {
          setApiError(result.errors)
        }

      })
    } else {
        socket.emit("update_coach", values, result =&amp;gt; {
        if (result.ok){
          setRefresh(!refresh)
          history.push(`/coaches/${result.data.id}`)
          setFormData(result.data)
          setApiError({})
        } else {
          setApiError(result.errors)
        }
      })
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above, the &lt;code&gt;socket.emit()&lt;/code&gt; function has three arguments: the name of the room, the data we are transmitting, and an optional acknowledgement. The acknowledgement we have to design and set up on the backend so that my app maintains the same code logic as before.&lt;/p&gt;

&lt;p&gt;On the backend, I originally had API routes to handle get / post requests and get / patch / delete requests. Using &lt;code&gt;socketio&lt;/code&gt;, I removed the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CoachesIndex(Resource):
    def get(self):
        coaches = Coach.query.all()
        response = make_response(
            coaches_schema.dump(coaches),
            200
        )
        return response

    def post(self):
        ch_data = request.get_json()

        del ch_data["id"]

        try:
            new_coach = Coach(**ch_data)
            db.session.add(new_coach)
            db.session.commit()

        except Exception as e:
            error_message = str(e)
            return {"errors" :  error_message }, 400

        response = make_response(
            coach_schema.dump(new_coach),
            201
        )

        return response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I register events that correspond to the frontend's emitting response, one for new objects being created, and another for objects being updated. For the coach path I created the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@socketio.on("new_coach")
def handle_new_coach(data):
    result = {
            "data" : None,
            "errors" : {},
            "ok" : False
                }

    del data["id"]

    try:
        new_coach = Coach(**data)
        db.session.add(new_coach)
        db.session.commit()
    except Exception as e:
        error_message = str(e)
        result["errors"] = error_message
        return result

    result["ok"] = True
    result["data"] = coach_schema.dump(new_coach)
    refresh_all_data()
    return result
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The data from the frontend can be received as a parameter within your function whereas before the data is received from the request object and pulled using &lt;code&gt;get_json()&lt;/code&gt; function. There are some other changes as well:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I create a result dictionary. here I mimic some of the response attributes the frontend is dependent on. &lt;/li&gt;
&lt;li&gt;if creating and submitting the data was successful to the DB, I call on that &lt;code&gt;refresh_all_data()&lt;/code&gt; function. When it runs, it emits data to the rooms I specified however, nothing happens yet... &lt;/li&gt;
&lt;li&gt;I return the result dictionary. In socketio for python, acknowledgements is provided through &lt;code&gt;return&lt;/code&gt;s at the end of your &lt;code&gt;socketio.on&lt;/code&gt; function&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the frontend, the component reads if the response is ok. This works similarly to previous way where I cause a change on the dependency array that the &lt;code&gt;useEffect&lt;/code&gt; utilizes (refresh variable). This causes the code within it to run, allowing the rooms to be read, and for my app to update.&lt;/p&gt;

&lt;p&gt;Thank you for reading my blog. While not the most common use of &lt;code&gt;socketio&lt;/code&gt;, implementing this technology was fun and interesting. I hope others who are on this journey can utilize some of the things I learned.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>websockets</category>
      <category>socketio</category>
      <category>flasksocketio</category>
    </item>
    <item>
      <title>Formik and how to create static and dynamic inputs</title>
      <dc:creator>Chris</dc:creator>
      <pubDate>Fri, 13 Oct 2023 16:08:45 +0000</pubDate>
      <link>https://dev.to/chris10garcia/formik-and-how-to-create-static-and-dynamic-inputs-2d93</link>
      <guid>https://dev.to/chris10garcia/formik-and-how-to-create-static-and-dynamic-inputs-2d93</guid>
      <description>&lt;p&gt;Formik is a lightweight library that makes building forms in React easier and more streamline. It helps with:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Managing values in state&lt;/li&gt;
&lt;li&gt;Handling form submission and resets&lt;/li&gt;
&lt;li&gt;Validation and error messages&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can create formik forms by either using &lt;code&gt;useFormik()&lt;/code&gt; hook or using the &lt;code&gt;&amp;lt;Formik /&amp;gt;&lt;/code&gt; component. For our example, we will be using the component version, which gives us access to various advanced features that can't be utilized using the hook version.&lt;/p&gt;

&lt;p&gt;For the purpose of this lesson, we will be covering the following&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creating a basic form with an input and selection field&lt;/li&gt;
&lt;li&gt;Creating a dynamic list of an input and selection field&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To start, install formik using your package manager (I used npm), and import the following modules into your React App: &lt;code&gt;import { Formik, Form, Field } from "formik"&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;To create your first form, we start with the &lt;code&gt;&amp;lt;Formik&amp;gt; &amp;lt;Formik /&amp;gt;&lt;/code&gt; component&lt;/p&gt;

&lt;p&gt;Next we will pass the following props into this component&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(){
  const colors = ["Red", "Green", "Blue", "White", "Black", "Yellow", "Orange"];
  const subjects = ["Calculus", "English Lit", "History", "Social Studies", "Physics"];
  const initialValues = {
    name: "",
    color: "",
   }
...
return (
     &amp;lt;Formik
        initialValues={initialValues}
        onSubmit={values =&amp;gt; alert(JSON.stringify(values, null, 3))} &amp;gt;


     &amp;lt;/ Formik&amp;gt;
)}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Within our app, we are creating an initialValues dictionary and passing that into the initialValues prop. We are also creating a list of colors and subjects to use later in our form. For our &lt;code&gt;onSubmit&lt;/code&gt;, we call a function and pass &lt;code&gt;values&lt;/code&gt; into an alert. This can also be a callback function written elsewhere in your App.&lt;/p&gt;

&lt;p&gt;Next, for a simple input and selection form, we will insert the following within the &lt;code&gt;&amp;lt;Formik&amp;gt; &amp;lt;/Formik&amp;gt;&lt;/code&gt; components:&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;Form &amp;gt;
     &amp;lt;label&amp;gt;Student Name&amp;lt;/label&amp;gt;
     &amp;lt;Field name="name" placeholder="Jane Doe" /&amp;gt;


     &amp;lt;label&amp;gt;Favorite Color&amp;lt;/label&amp;gt;
     &amp;lt;Field name="color" as="select"&amp;gt;
          &amp;lt;option label="Make a section" value="" /&amp;gt;
          { colors.map(color =&amp;gt; &amp;lt;option key={color} label={color} value={color} /&amp;gt;) }
     &amp;lt;/Field&amp;gt;


     &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
&amp;lt;/Form&amp;gt;


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

&lt;/div&gt;



&lt;p&gt;Now you have a basic form that manages the values of all of your inputs and passes them into a function when you submit it. The first &lt;code&gt;&amp;lt;Field /&amp;gt;&lt;/code&gt; manages the data that gets passed into the "name" key of your initialValues. The second &lt;code&gt;&amp;lt;Field &amp;gt; &amp;lt;/ Field&amp;gt;&lt;/code&gt; manages your selection. The child components are: the first one is an option element with a blank value. The second is a map of the colors list where each color gets assigned its own option value. Last, you have a button whose type is "submit". You do not need to explicitly state what your onClick does as Formik captures this as your onSubmit. However, you can control this action.&lt;/p&gt;

&lt;p&gt;Now to use more advanced features of formik, we will convert our code so that the &lt;code&gt;&amp;lt;Formik&lt;/code&gt;&amp;gt; component accepts a function as its children (this is formally known as a render prop).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;     {formik =&amp;gt; (
          &amp;lt;Form &amp;gt;
            &amp;lt;label&amp;gt;Student Name&amp;lt;/label&amp;gt;
            &amp;lt;Field name="name" placeholder="Jane Doe" label="Student Name" /&amp;gt; &amp;lt;br /&amp;gt; &amp;lt;br /&amp;gt;


            &amp;lt;label&amp;gt;Favorite Color&amp;lt;/label&amp;gt;
            &amp;lt;Field name="color" as="select"&amp;gt;
              &amp;lt;option label="Make a section" value="" /&amp;gt;
              {colors.map(color =&amp;gt; &amp;lt;option key={color} label={color} value={color} /&amp;gt;)}
            &amp;lt;/Field&amp;gt; &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt; &amp;lt;br /&amp;gt;

            &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
          &amp;lt;/Form&amp;gt;
    )}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using this gives us access to quite a few props that handle submitting your data, handling change, counting submissions, etc. &lt;/p&gt;

&lt;p&gt;If you're curious to see all of the props that get passed down, add a &lt;code&gt;{console.log(formik)}&lt;/code&gt; to your code within this function.&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%2F0zoe5um9yd2rd79si199.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%2F0zoe5um9yd2rd79si199.png" alt="Image description" width="247" height="356"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To get a full list and understanding of the formik prop library, go to their documentation page.&lt;/p&gt;

&lt;p&gt;Now to make our form dynamic.&lt;/p&gt;

&lt;p&gt;Include &lt;code&gt;FieldArray&lt;/code&gt; within your formik imports. Next, change your initialValues dictionary to include a third key where the values are an array of dictionary objects&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const initialValues = {
    name: "",
    color: "",
    records: [{ subject: "", grade: "" }]
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Within the render prop, below the 2nd field and above the submit button, we will add our &lt;code&gt;&amp;lt;FieldArray name="records"&amp;gt; &amp;lt;/ FieldArray&amp;gt;&lt;/code&gt; Component. We pass "records" as the name of our array, which is the same key name within our initialValues dictionary.&lt;/p&gt;

&lt;p&gt;Next you are creating another render prop within the &lt;code&gt;&amp;lt;FieldArray&amp;gt;&lt;/code&gt; component.&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;FieldArray&amp;gt;
     {({remove, push }) =&amp;gt; (
          &amp;lt;div&amp;gt;


          &amp;lt;/div&amp;gt;
     )}
&amp;lt;/ FieldArray&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the purposes of our blog, we will only use the remove, and push prop functions. &lt;/p&gt;

&lt;p&gt;Now to make this dynamic, we will utilize the following code within the div&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{formik.values.records.length &amp;gt; 0 &amp;amp;&amp;amp; formik.values.records.map((record, index) =&amp;gt; (
    ...
))}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We need to map the records array however, if there are no elements, javascript will give you an error. So to prevent this, you'll need to use a logical &lt;code&gt;AND&lt;/code&gt; statement and start it by testing the length of the array as greater than 0. If this evaluates to true, then you can map the array as your 2nd operand. A returned mapped list will result in a truthy result. A logical AND statement where both operands are truthy will result in the value of the last operand returned, which in our case, is the returned map results.&lt;/p&gt;

&lt;p&gt;Here is complete code within this block:&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;div&amp;gt;
{formik.values.records.length &amp;gt; 0 &amp;amp;&amp;amp; formik.values.records.map((record, index) =&amp;gt; (
     &amp;lt;div key={index}&amp;gt;


          &amp;lt;label&amp;gt;Grade Value&amp;lt;/label&amp;gt;
          &amp;lt;Field name={`records.${index}.grade`} /&amp;gt;


          &amp;lt;label&amp;gt;Subject&amp;lt;/label&amp;gt;
          &amp;lt;Field name={`records.${index}.subject`} as="select"&amp;gt;
               &amp;lt;option label="Make a section" value="" /&amp;gt;
               {subjects.map(subject =&amp;gt; &amp;lt;option key={subject} label={subject} value={subject} /&amp;gt;)}
          &amp;lt;/Field&amp;gt; 


          &amp;lt;button type="button" onClick={() =&amp;gt; remove(index)}&amp;gt;Remove&amp;lt;/button&amp;gt;
     &amp;lt;/div&amp;gt;
))}
&amp;lt;button type="button" onClick={() =&amp;gt; push({ grade: "", subject: "" })}&amp;gt;Add More&amp;lt;/button&amp;gt;
&amp;lt;/ div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is similar to our first simple form example except the following important details:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;for both field names, it needs to be dynamic. The name is the records array, the index number, and the key you're accessing. &lt;/li&gt;
&lt;li&gt;A button is within the map, which the purpose is to use the remove prop. map allows you to access the element's index as the second argument. So passing this into the remove function removes the specific element within the array&lt;/li&gt;
&lt;li&gt;A button is outside of map but within the our fieldArray render prop. This button adds to the array by pushing an element that contains keys to blank values.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When you submit your form now, you can see the values of your static list and also the values of your dynamic list.&lt;/p&gt;

&lt;p&gt;I hope this has been a helpful posting. I created the above form with some minor formatting as a codesandbox. Check it out below&lt;/p&gt;

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

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/blogapp-3gxgkw"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>react</category>
      <category>reactforms</category>
      <category>formik</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Understanding List, Set, and Dictionary Comprehension in Python</title>
      <dc:creator>Chris</dc:creator>
      <pubDate>Sun, 30 Jul 2023 00:18:08 +0000</pubDate>
      <link>https://dev.to/chris10garcia/understanding-list-set-and-dictionary-comprehension-in-python-2nc5</link>
      <guid>https://dev.to/chris10garcia/understanding-list-set-and-dictionary-comprehension-in-python-2nc5</guid>
      <description>&lt;p&gt;List comprehensions in python is a powerful tool that allows you to create lists, sets, and dictionaries with a single line of code. When using list comprehensions to create your lists, you can utilize conditional logic, expressions, and callbacks functions to control the output of the elements pushed into the new list.&lt;/p&gt;

&lt;p&gt;There are many ways of creating lists in python. We will specifically discuss for loops, list comprehensions and how the two are similar.&lt;/p&gt;

&lt;p&gt;To create a list using a for loop, you must&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Instantiate an empty list&lt;/li&gt;
&lt;li&gt;Loop over an iterable (such as a list, tuple, range, or dictionary object)&lt;/li&gt;
&lt;li&gt;Append each element to the end of the list&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using a for loop, let's create a list that contains the double of values 0 - 10:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;double = []
for i in range(11):  
    result = i * 2
    double.append(result)
double
# &amp;gt;&amp;gt;&amp;gt; [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using list comprehension, we can simplify this into one line of code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;double = [ i * 2 for i in range(11) ]
double
# &amp;gt;&amp;gt;&amp;gt; [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To filter which value gets doubled, we can add a conditional if statement. We only want even numbers to be doubled and stored in the list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;double = []
for i in range(11):
    if i % 2 == 0:
        result = i * 2
        double.append(result)
double
# &amp;gt;&amp;gt;&amp;gt; [0, 4, 8, 12, 16, 20]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With list comprehension:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;double = [ i * 2 for i in range(11) if i % 2 == 0]
double
# &amp;gt;&amp;gt;&amp;gt; [0, 4, 8, 12, 16, 20]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also add an else clause and make it an if expression; if the value is even, double it, else return another thing (let’s use the word "hi" ). Note, the structure of the list comprehension will be different:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;double = [ i * 2 if i % 2 == 0 else "hi" for i in range (11)]
# &amp;gt;&amp;gt;&amp;gt; [0, 'hi', 4, 'hi', 8, 'hi', 12, 'hi', 16, 'hi', 20]

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

&lt;/div&gt;



&lt;p&gt;The reason for this is due to the syntax of a list comprehension:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new_list = [ expression for item in iterable optional_if_condition ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;List comprehension are structured using three important components as well as an optional fourth:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;an expression&lt;/li&gt;
&lt;li&gt;the item&lt;/li&gt;
&lt;li&gt;the iterable&lt;/li&gt;
&lt;li&gt;optional if statement&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The expression can be the item itself, a call to a function, or any expression that returns a value. For instance, you can have a list with 10 "hi": &lt;code&gt;greetings = ["hi" for i in range(11)]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The item is the element in the iterable.&lt;/p&gt;

&lt;p&gt;The iterable can be a list, set, dictionary, range, or any object that can return its elements one at a time.&lt;/p&gt;

&lt;p&gt;The optional if statement acts as a filter. If the conditional evaluates to True, the expression component evaluates and the return value gets pushed into the list, otherwise the expression does not run for that round of the iteration. Using the above example, you can have a list with 10 "hi" if your conditional is "if True" or a blank list if your conditional is "if False". For complex filters, a function can be used to do your analysis.&lt;/p&gt;

&lt;p&gt;The benefits of using list comprehension are that you can use a single tool in many situations to create lists. In JavaScript, you can create new lists utilizing the .map() and .filter() methods. However, there isn't a method that combines the two. Python also has .map() and .filter() methods as well. But fortunately in python, with list comprehension, you have 1 tool that can utilize both methods at your disposal.&lt;/p&gt;

&lt;p&gt;Python contains other list data structures and you can apply comprehension to them as well. I will specifically cover set and dictionary comprehension. &lt;/p&gt;

&lt;p&gt;Set and dictionary comprehension are similar to each other. Both set and dictionary use curly brackets and outputs unique elements into an unordered list but with dictionaries, you must also include values that corresponds to the key.&lt;/p&gt;

&lt;p&gt;The syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new_set = { expression for item in iterable optional_if_condition }
new_dict = { key_expression : value_expression for item in iterable optional_if_condition }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's create a set list where it contains the letters of a sentence&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sentence = "Today, we are learning list, set, and dictionary comprehension"
set_sentence = { item for item in sentence}
set_sentence
# &amp;gt;&amp;gt;&amp;gt; {',', 'l', 'm', 'T', 'r', 'a', 'e', 'n', 'i', 't', 'c', ' ', 's', 'p', 'd', 'o', 'y', 'w', 'h', 'g'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's create a dictionary where the key is the letter and the value is the count of each character in the sentence.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;set_sentence = { item : sentence.count(item) for item in sentence}
set_sentence
# &amp;gt;&amp;gt;&amp;gt; {'T': 1, 'o': 4, 'd': 3, 'a': 5, 'y': 2, ',': 3, ' ': 8, 'w': 1, 'e': 6, 'r': 4, 'l': 2, 'n': 6, 'i': 5, 'g': 1, 's': 3, 't': 3, 'c': 2, 'm': 1, 'p': 1, 'h': 1}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally for dictionary comprehension, you can use 2 items if the iterable returns two values. For instance, we can create a dictionary &lt;code&gt;enumerating&lt;/code&gt; a list or using .items() method on an existing dictionary.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fruits = ["apples", "bananas", "grapes", "oranges", "pineapples"]
fruit_dict = { key : value for key, value in enumerate(fruits)}
fruit_dict
# &amp;gt;&amp;gt;&amp;gt; {0: 'apples', 1: 'bananas', 2: 'grapes', 3: 'oranges', 4: 'pineapples'}

phone_book = {"John" : 3334445555, "Rose" : 5555555555, "Alan" : 1234567890}
phone_book_edit = { key.upper() : value for key, value in phone_book.items()}
# &amp;gt;&amp;gt;&amp;gt; {'JOHN': 3334445555, 'ROSE': 5555555555, 'ALAN': 1234567890}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope my guide helped you on your programming journey. Please feel free to comment, ask questions, or provide feedback.&lt;/p&gt;

&lt;p&gt;Lastly, happy coding!&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>datastructures</category>
      <category>productivity</category>
    </item>
    <item>
      <title>An Overview on how to use State in React</title>
      <dc:creator>Chris</dc:creator>
      <pubDate>Fri, 12 May 2023 20:04:42 +0000</pubDate>
      <link>https://dev.to/chris10garcia/an-overview-on-how-to-use-state-in-react-40gk</link>
      <guid>https://dev.to/chris10garcia/an-overview-on-how-to-use-state-in-react-40gk</guid>
      <description>&lt;p&gt;In React, a virtual DOM is created to allow more efficient browser DOM manipulation and re-renderings. To allow React to know which components to update when a change in information occurs, it utilizes "state". State of a component is an object that holds information that may change over time and / or due to interactions by the user. This allows React to know when to re-render the component. And within a recent update to React, hooks are introduced to allow you to use state and other React features easier without writing a class (&lt;a href="https://legacy.reactjs.org/docs/hooks-intro.html"&gt;https://legacy.reactjs.org/docs/hooks-intro.html&lt;/a&gt;). &lt;/p&gt;

&lt;p&gt;Before we begin, there are some import rules for hooks (like useState and others)&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Only call hooks at the top level of a function component. Think of it similarly to the import statement&lt;/li&gt;
&lt;li&gt;You can't call hooks inside loops or conditions.&lt;/li&gt;
&lt;li&gt;Hooks can only be called from React Functions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's say you have a button, and every time you click it, it increases a counter. In vanilla JS you would have to&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;create an event listener and attached to the button element&lt;/li&gt;
&lt;li&gt;go into the DOM and access the element that contains the counter value&lt;/li&gt;
&lt;li&gt;increment it&lt;/li&gt;
&lt;li&gt;and then append the element&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's do this instead using React. Let's write out our basic Component.&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 CounterExample(){
    let counter = 0

    return(
        &amp;lt;div&amp;gt;
            &amp;lt;h1&amp;gt;You have clicked the button {counter} times so far!&amp;lt;/h1&amp;gt;
            &amp;lt;button&amp;gt;Click me&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;First, we need to import useState from the react library.&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;Next, we need to call on useState, which the argument it accepts will be the initial value of your 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;const [counter, setCounter] = useState(0)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are a few things going on with the above line of code. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First, useState returns a 2-element array. The first element is the state variable with the initial argument you passed into the useState function. The second element is the setter function that sets the first element's value. You cannot assign a new value directly to the state variable. Instead, you use the setter function to set the value. This is how React knows when to re-render the component&lt;/li&gt;
&lt;li&gt;Second, the above line uses JS destructuring. You can separate the elements of an array or properties of an object into separate variables all within 1 line. In the above case, the first element is the state variable and the second is the setter function&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Important note, it is a common programming pattern to add the word "set" in front of the state variable name when assigning it as the setter function. So "formData", "counter", "color" will be "setFormData", "setCounter", "setColor", etc. &lt;/p&gt;

&lt;p&gt;Next, we need to create our React event listener and increment our 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;import React from 'react'

function CounterExample(){
    const [counter, setCounter] = useState(0)

    return(
        &amp;lt;div&amp;gt;
            &amp;lt;h1&amp;gt;You have clicked the button {counter} times so far!&amp;lt;/h1&amp;gt;
            &amp;lt;button onClick = { () =&amp;gt; setCounter(counter+1)} &amp;gt; Click me&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;We're passing a callback function that increases the value of counter by 1. As mentioned before, you can't just assign a new value to counter. Instead, you need to pass a new value to setCounter. React will update the state variable and know to re-ender that component.&lt;/p&gt;

&lt;p&gt;Now every time you press the button, the counter value increases and gets updated within the DOM.&lt;/p&gt;

&lt;p&gt;When using forms, you need to capture the input values using state. However, if you have multiple inputs, using so many state variables can become convoluted. Besides passing single values, you can pass arrays or objects into state and state setter functions&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;import React from 'react'

function CounterExample(){
    const [counter, setCounter] = useState(0)

    return(
        &amp;lt;form&amp;gt;
            &amp;lt;input name = "firstName" type = "text" placeholder="First Name Here" /&amp;gt;
            &amp;lt;input name = "lastName" type = "text" placeholder="Last Name Here" /&amp;gt;
            &amp;lt;input name = "age" type = "number" placeholder="age" /&amp;gt;
            &amp;lt;button&amp;gt;Submit Values &amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;instead of creating multiple state's, you can create 1 state to capture all three inputs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [form, setFormData] = useState( {"firstName": "", "lastName" : "", "age" : "" })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, when you create your event listener for each input, you can create 1 event listener that accesses the key value pair within the object and update it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function handleOnChange(e){
    const key = e.target.name
    const value = e.target.value

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

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

&lt;/div&gt;



&lt;p&gt;Please note, if you are using objects or arrays with state, you need to pass a COPY of it. You cannot use mutable array methods. However, you can "spread" the array or object into the setter function. &lt;/p&gt;

&lt;p&gt;The final set of code will be:&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 CounterExample(){
    const [form, setFormData] = useState( {"firstName": "", "lastName" : "", "age" : "" })

    return(
        &amp;lt;form onSubmit = {submitCallBackFunction}&amp;gt;
            &amp;lt;input onChange = {handleOnChange} name = "firstName" type = "text" placeholder="First Name Here" value={formData["firstName"]}/&amp;gt;
            &amp;lt;input onChange = {handleOnChange} name = "lastName" type = "text" placeholder="Last Name Here" value={formData["lastName"]}/&amp;gt;
            &amp;lt;input onChange = {handleOnChange} name = "age" type = "number" placeholder="age" value={formData["age"]}/&amp;gt;
            &amp;lt;button&amp;gt;Submit Values &amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;Lastly, you should declare your state variables within the component that will use them. However, if another component needs to use this variable, then the closet parent to both is where state needs to reside, and then brought down via props.&lt;/p&gt;

&lt;p&gt;The best way to brainstorm this is to create a component map.&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
|--- App
    |--- Header
    |--- DisplayData
    |--- AddData
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;DisplayData needs a state variable to display some data. However, AddData contains data that will eventually be added to the state variable within DisplayData. So, App will contain the state data variable and then passed that down to DisplayData while passing down the setter function to the AddData component.&lt;/p&gt;

&lt;p&gt;Also, AddData contains forms which need to be controlled. A separate state variable will be needed to keep tract of the input values. However, based on how our app is configured, it can stay within this component. When the user presses submit, a callback function or the setter function can be passed down to add the new data to the data state variable.&lt;/p&gt;

&lt;p&gt;Our new map will look like this. (Please note you can design your map however you like but make it so that it shows a logical map of where your state variables are established!)&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
|--- App (data, setData)
    |--- Header
    |--- DisplayData &amp;lt;- data |
    |--- AddData &amp;lt;- setData | (formData, setFormData)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, when react re-renders the component where the state variable is assigned, it will render every child component underneath it as well but not parent or sibling components.&lt;/p&gt;

&lt;p&gt;I hope my above guide helped you on your programming journey.&lt;/p&gt;

&lt;p&gt;Lastly, happy coding!&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>state</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Remember To Take Into Consideration Pass by Value Vs Pass By Reference When Working With JSON data</title>
      <dc:creator>Chris</dc:creator>
      <pubDate>Mon, 13 Mar 2023 22:27:27 +0000</pubDate>
      <link>https://dev.to/chris10garcia/remember-to-take-into-consideration-pass-by-value-vs-pass-by-reference-when-working-with-json-data-2iaj</link>
      <guid>https://dev.to/chris10garcia/remember-to-take-into-consideration-pass-by-value-vs-pass-by-reference-when-working-with-json-data-2iaj</guid>
      <description>&lt;p&gt;For my phase 1 final project of the Flatiron Software Engineering Bootcamp, I created a single page website that displays the breweries of New York City. I used a public API from &lt;a href="https://www.openbrewerydb.org/"&gt;Open Brewery DB&lt;/a&gt; but needed to filter the massive dataset down to just breweries located within the city. To accomplish this, I first acquired a CSV file with all of the zip codes of NYC and created a dictionary object using this data. Breweries that matched with the NYC zip code were pushed into a new array and eventually saved into its own db.json file. While I was able to do this successfully, I noticed some wonky behavior concerning some the arrays and objects I created and the various iterative methods I called on them. After deep diving into the problem and debugging the issue, I figured out the cause of this buggy behavior; I was not taking into consideration pass by value and pass by reference.&lt;/p&gt;

&lt;p&gt;Before I begin, I want to provide a quick review of the iterative methods I used frequently to complete my labs, homework’s, and final project: &lt;code&gt;.map()&lt;/code&gt;, &lt;code&gt;.filter()&lt;/code&gt;, and &lt;code&gt;.forEach()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;array.map()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;How &lt;code&gt;.map()&lt;/code&gt; works: it takes the elements within the array it was called on, does something to each element with a function you provide, and returns the processed elements in a new array. The original array stays the same&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myArray = [0, 1, 2, 3, 4, 5]

const result = myArray.map(element =&amp;gt; {
    return element * 2
})

console.log("The new array is: ")
console.log(result)

console.log("The original array is: ")
console.log(myArray)

// The new array is: 
// [0, 2, 4, 6, 8, 10]
// The original array is: 
// [0, 1, 2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;code&gt;array.filter()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;How &lt;code&gt;.filter()&lt;/code&gt; works: it takes the elements within the array it was called on, and runs each element through some conditional statement or function, and if it returns true, places the original element into a new array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myArray = [0, 1, 2, 3, 4, 5]

const result = myArray.filter(element =&amp;gt; {
    element = element * 2
    return element &amp;gt; 3
})

console.log("The new array is: ")
console.log(result)

// The new array is: 
// [2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that even though each element was doubled, the original value of the element was pass into the array.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;array.forEach()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;How &lt;code&gt;.forEach()&lt;/code&gt; works: it takes the elements within the array, and does something to each one with a function you provide. It sounds similar to &lt;code&gt;.map()&lt;/code&gt; except &lt;code&gt;.forEach()&lt;/code&gt; doesn't return the element or processed element. You can declare a variable, array, etc. outside of the function and assign or push the element into this variable (but then it is better to use &lt;code&gt;.map()&lt;/code&gt; in this case). &lt;code&gt;.forEach()&lt;/code&gt; is useful if you are calling a function on each element but do not need to return a new array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myArray = [0, 1, 2, 3, 4, 5]

const result_1 = []

const result_2 = myArray.forEach(element =&amp;gt; {
  element = element * 3
  result_1.push(element)
  return element
})

console.log("original: ")
console.log(myArray)

console.log("result_1: ")
console.log(result_1)

console.log("result_2: ")
console.log(result_2)
// original: 
// [ 0, 1, 2, 3, 4, 5 ]
// result_1: 
// [ 0, 3, 6, 9, 12, 15 ]
// result_2: 
// undefined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What does this have to do with pass by value vs pass by reference?&lt;/p&gt;

&lt;p&gt;&lt;code&gt;myArray&lt;/code&gt; was an array of integers, and integers are primitive values. When you pass a primitive value into a function, a copy of that value gets passed in. You can change the variable within the function but it doesn't change the variable outside of the function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function double (x) {
    x = x * 2
    return x;
}

let y = 100; 
let result = double(y)

console.log(y) // 100
console.log(result) // 200
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When working with JSON data, you have an array of OBJECTS, an important distinction here. Objects are passed by reference in JavaScript. What this means is JavaScript passes the direct location / address in memory where the object is located into the function, not a copy of it. If you change a property of an object within the function, it persists outside of the function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function doubleProperty(obj){
    obj.value = obj.value * 2
    return obj // 
}

const myObj = {value : 10}

console.log("Original object: ")
console.log(myObj)

const result = doubleProperty(myObj)

console.log("New resulting object: ")
console.log(result)

console.log("Original object: ")
console.log(myObj)

// Original object: 
// { value: 10 }
// New resulting object: 
// { value: 20 }
// Original object: 
// { value: 20 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And even if you remove the &lt;code&gt;return&lt;/code&gt; statement, the results are still the same: the original object will get modified. This needs to be taken into account when calling on iterative methods such as &lt;code&gt;.map()&lt;/code&gt;, &lt;code&gt;.filter()&lt;/code&gt;, and &lt;code&gt;.forEach()&lt;/code&gt; on JSON data! &lt;/p&gt;

&lt;p&gt;Here is an example. You have json data with the following structure:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;{studentName, favoriteColor, favoriteNumber}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you want to double each student's favorite number and store it in a new array, I would have originally written:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const studentsArray = [{
    "studentName" : "Chris",
    "favoriteColor" : "blue",
    "favoriteNumber" : "15" 
    },
    {
    "studentName" : "Rose",
    "favoriteColor" : "blue",
    "favoriteNumber" : "36" 
    }]


const results = studentsArray.map(studentObj =&amp;gt; {
    const newObj = studentObj
    newObj.favoriteNumber = newObj.favoriteNumber * 2
    return newObj
})

console.log("original: ")
console.log(studentsArray)

console.log("updated: ")
console.log(results)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which results:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;original: 
[
  { studentName: 'Chris', favoriteColor: 'blue', favoriteNumber: '30' },
  { studentName: 'Rose', favoriteColor: 'blue', favoriteNumber: '72' }
]
updated: 
[
  { studentName: 'Chris', favoriteColor: 'blue', favoriteNumber: 30 },
  { studentName: 'Rose', favoriteColor: 'blue', favoriteNumber: 72 }
]:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even if you do not intend on using the original array, for better coding practices, one should take this problem into consideration. Fortunately, there is a way to solve this issue: using the spread operator &lt;code&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;const results = studentsArray.map(studentObj =&amp;gt; {
    const newObj = {...studentObj}
    newObj.favoriteNumber = newObj.favoriteNumber * 2
    return newObj
})

console.log("original: ")
console.log(studentsArray)

console.log("updated: ")
console.log(results)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which results:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;original: 
[
  { studentName: 'Chris', favoriteColor: 'blue', favoriteNumber: '15' },
  { studentName: 'Rose', favoriteColor: 'blue', favoriteNumber: '36' }
]

updated: 
[
  { studentName: 'Chris', favoriteColor: 'blue', favoriteNumber: 30 },
  { studentName: 'Rose', favoriteColor: 'blue', favoriteNumber: 72 }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One function of the spread operator is to COPY the contents of an array or object and spreads it into a corresponding new array or new object. If you then make a change to the new array or object, the original stays intact.&lt;/p&gt;

&lt;p&gt;I hope this blog post helps with your journey. Thanks for reading and happy coding!&lt;/p&gt;

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