<?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: gisellec60</title>
    <description>The latest articles on DEV Community by gisellec60 (@gisellec60).</description>
    <link>https://dev.to/gisellec60</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%2F1073978%2F0a331b31-400a-44fc-a30c-6b4d7fc1595d.png</url>
      <title>DEV Community: gisellec60</title>
      <link>https://dev.to/gisellec60</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/gisellec60"/>
    <language>en</language>
    <item>
      <title>Shortcuts</title>
      <dc:creator>gisellec60</dc:creator>
      <pubDate>Sat, 17 Aug 2024 17:34:57 +0000</pubDate>
      <link>https://dev.to/gisellec60/shortcuts-4af</link>
      <guid>https://dev.to/gisellec60/shortcuts-4af</guid>
      <description>&lt;p&gt;&lt;iframe src="https://player.vimeo.com/video/845781088" width="710" height="399"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Fetch API</title>
      <dc:creator>gisellec60</dc:creator>
      <pubDate>Mon, 09 Oct 2023 00:27:50 +0000</pubDate>
      <link>https://dev.to/gisellec60/fetch-api-270j</link>
      <guid>https://dev.to/gisellec60/fetch-api-270j</guid>
      <description>&lt;p&gt;&lt;strong&gt;&lt;em&gt;Fetch API&lt;/em&gt;&lt;/strong&gt; - One of the requirements for my phase-5 capstone project with FlatIron School was to write a technical blog. I could'nt decide what to write about since the list of topics seemed endless. However, as I began to develop my app, I found myself running into problems with handling responses coming Fetch API. It didn't take long for me to  realize I didn't understand how it worked. I knew there was something called the &lt;strong&gt;promise&lt;/strong&gt; and it had something to do with &lt;strong&gt;response ojects&lt;/strong&gt; being return and &lt;strong&gt;.then()&lt;/strong&gt; running aftwards, but I was just fudging my way through, throwing code and the wall and seeing what stuck so to speak. I found I was taking so much time working through those errors that it chewed up precious time better spent writing and perfecting functionality. Hence, &lt;strong&gt;The Promise...&lt;/strong&gt;&lt;strong&gt;&lt;em&gt;Then&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Fetch API&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Fetch API is an interface to getting or &lt;em&gt;fetching&lt;/em&gt; resources. Fetch() requires one argument which is the path to the resource you want to fetch. It's a powerful way to make HTTP request in Javascript. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Promises:&lt;/em&gt;&lt;/strong&gt; &lt;br&gt;
A promise is an JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.&lt;/p&gt;

&lt;p&gt;A Promise may have one of three states:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;Pending&lt;/em&gt;: The initial state; neither filled nor rejected.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Fulfilled&lt;/em&gt; : The operation completed sucessfully and the resulting value is available&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Rejected&lt;/em&gt;: The operation failed, and an error reason is available. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A promise starts in a &lt;em&gt;pending&lt;/em&gt; state. That means the process is not complete. If the operation is successful, the process ends in a &lt;em&gt;fulfilled&lt;/em&gt; state. And, if an error occurs, the process ends in a &lt;em&gt;rejected&lt;/em&gt; state.&lt;/p&gt;

&lt;p&gt;For example, when you request data from the server by using a promise, it will be in a pending state. When the data arrives successfully, it will be in a fulfilled state. If an error occurs, then it will be in a rejected state. You can attach callbacks to a Promise using the .then() and .catch() methods. The &lt;strong&gt;&lt;em&gt;.then() method is called when the Promise is fulfilled, while the .catch() method is called when the Promise is rejected.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In my research I found there's alot that can be said about promises. You can actually create them but that's beyond the scope of this blog. Right now I want to discuss how to make use of them in conjunction with Fetch API!!! &lt;strong&gt;&lt;em&gt;So let's get to it!!!&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Using the Fetch API&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
The Fetch API really is simple to use. You call fetch() and provide the url of the resource you're trying to fetch. The fetch() returns a promise that resovles to a response object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://api.example.com/data')
  .then(response =&amp;gt; {
    console.log(response);
  })
  .catch(error =&amp;gt; {
    console.error('Error fetching data:', error);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, we are fetching data from &lt;a href="https://api.example.com/data"&gt;https://api.example.com/data&lt;/a&gt;. The fetch() method returns a &lt;em&gt;Promise&lt;/em&gt;(* in the fulfilled state that resovles to a response*), and we are using the .then() method to handle the successful response and the .catch() method to handle any errors.&lt;/p&gt;

&lt;p&gt;The Response object that we receive in the .then(&lt;em&gt;response&lt;/em&gt;) method contains several properties and methods that can be used to extract the data from the response object. Some of the most commonly used properties and methods are as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;response.ok:&lt;/em&gt;&lt;/strong&gt; A boolean value that indicates whether the request was successful (status code in the range 200-299) or not.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;response.status:&lt;/em&gt;&lt;/strong&gt; The status code of the response (e.g., 200, 404, 500, etc.).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;response.statusText:&lt;/em&gt;&lt;/strong&gt; A status message corresponding to the status code (e.g., "OK", "Not Found", "Internal Server Error", etc.).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;response.headers:&lt;/em&gt;&lt;/strong&gt; An object representing the headers of the response.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;response.json():&lt;/em&gt;&lt;/strong&gt; A method that returns a Promise that resolves to the JSON object resulting from parsing the response's body text as JSON.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;response.text():&lt;/em&gt;&lt;/strong&gt; A method that returns a Promise that resolves to the response's body text as a string.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        fetch(`/dancers/${values["email"]}?action=none`)
        .then(res =&amp;gt; {
            if (!res.ok){ 
                throw new Error('Network response was not ok');
             }
             return Response.json() //Returns a promise that resolves to Json data
            })    
        .then((dancer) =&amp;gt; {     
            setDancer(dancer)
            handleShowDancer()
        }) 
        .catch(error =&amp;gt; {
            console.log("Error Returned",error);    
            // onError(error) 
            setError(error)
        })
    }

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

&lt;/div&gt;



&lt;p&gt;In this example (&lt;em&gt;using code from my app&lt;/em&gt;), we first check if the response.ok property is true. If it is not, we throw an error that will be caught by the .catch() method. Otherwise, we call the response.json() method, which returns a Promise that resolves to a response that is then resolved to the JSON data. We then use another .then() method to handle the JSON data.  &lt;/p&gt;

&lt;p&gt;The idea that we can fetch data in other formats, like text and binary data(images, audio, files etc) also intrigued me.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://api.example.com/data.txt')
  .then(response =&amp;gt; {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.text(); // text instead of json
  })
  .then(text =&amp;gt; {
    console.log(text);
  })
  .catch(error =&amp;gt; {
    console.error('Error fetching data:', error);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fetch with Async/Await&lt;br&gt;
Another technique I've been very curious about is Async/Await. This is another way I've seen the fetch method used. According to the documentation I just read we:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Declare an async function. This tells JavaScript that the  function will contain asynchronous code.&lt;/li&gt;
&lt;li&gt;Inside the async function, use the await keyword before calling the fetch() method. This tells JavaScript to wait for the Promise to resolve before continuing with the rest of the code.&lt;/li&gt;
&lt;li&gt;Use try/catch blocks to handle errors.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchData();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we declare an async function called fetchData. Inside the function, we use the &lt;strong&gt;await&lt;/strong&gt; keyword before calling the fetch() method and the response.json. &lt;/p&gt;

&lt;p&gt;Giselle Smith is a FullStack Software Developer Engineer student at &lt;a href="https://flatironschool.com/"&gt;Flatiron School&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;References:&lt;br&gt;
&lt;a href="https://semaphoreci.com/blog/asynchronous-javascript#:~:text=Asynchronicity%20means%20that%20if%20JavaScript,callback%20queue%20and%20event%20loop."&gt;Asynchronous JavaScript for Beginners&lt;/a&gt;&lt;br&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises"&gt;How to use promises&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.altcademy.com/blog/how-to-use-the-javascript-fetch-api-to-get-data/"&gt;https://www.altcademy.com/blog/how-to-use-the-javascript-fetch-api-to-get-data/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>asynchronous</category>
      <category>fetch</category>
      <category>promise</category>
    </item>
    <item>
      <title>The Scheduler</title>
      <dc:creator>gisellec60</dc:creator>
      <pubDate>Thu, 24 Aug 2023 20:14:14 +0000</pubDate>
      <link>https://dev.to/gisellec60/the-scheduler-hc7</link>
      <guid>https://dev.to/gisellec60/the-scheduler-hc7</guid>
      <description>&lt;p&gt;&lt;strong&gt;&lt;em&gt;The Scheduler&lt;/em&gt;&lt;/strong&gt; was born out of the need for a more robust volunteer scheduling system for my church. The app manages the scheduling of the volunteers by enabling a user to add, modify, and delete a volunteer or schedule, and query the schedule by date or username. Ideally only people with admin privileges will be able to make any changes to the schedule, but everyone will be able to query the schedule. Currently there are no admin privileges set for the app so everyone has full access.&lt;/p&gt;

&lt;p&gt;The Scheduler consist of 4 tables: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Volunteer&lt;/li&gt;
&lt;li&gt;Schedule&lt;/li&gt;
&lt;li&gt;Role&lt;/li&gt;
&lt;li&gt;Volunteers_Role&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Diagram table relationships:&lt;/p&gt;

&lt;p&gt;fig(1)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--a0dhIuE3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfg39twszx6dkep9007s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--a0dhIuE3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfg39twszx6dkep9007s.png" alt="diagram" width="527" height="315"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Schedule
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Schedule(Base):
    __tablename__ = 'schedules'

    id = Column(Integer, primary_key=True)
    date = Column(DATE, nullable=False)
    swappout_id = Column(Integer,nullable=True)

    vol_id = Column(Integer, ForeignKey('volunteers.id'))
    role_id = Column(Integer, ForeignKey('roles.id'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;fig(2)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--asxT-6ox--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jzfr8gsj82q5zyrttuli.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--asxT-6ox--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jzfr8gsj82q5zyrttuli.png" alt="schdule_table" width="800" height="221"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Because Schedule has a one-to-many relationship with Volunter and Role, foreign keys were created for both tables to manage the relationship&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Example One-to-Many&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ipdb&amp;gt;    schedule = session.query(Schedule).filter(Schedule.date == "2023-08-16").all()

ipdb&amp;gt; schedule
[Schedule: 3, Swapped: 19, Volunteer: 5, Role: 4, Date: 2023-08-16 , Schedule: 29, Swapped: , Volunteer: 7, Role: 2, Date: 2023-08-16 ]

ipdb&amp;gt; [sched.vol_id for sched in schedule]
[5, 7]

ipdb&amp;gt;  [sched.role_id for sched in schedule]
[4, 2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because schedule object returned a list (&lt;em&gt;one-to-many&lt;/em&gt;)  I iterated over the list using a list comprehension to pull out the volunteer ids. Notice that one instance of schedule also return multiple role ids.&lt;/p&gt;

&lt;h2&gt;
  
  
  Volunteer
&lt;/h2&gt;

&lt;p&gt;fig(3)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Volunteer(Base,Validate):
    __tablename__ = "volunteers"

    id = Column(Integer, primary_key=True)
    first_name = Column(String, nullable=False)
    last_name = Column(String, nullable=False)

    email = Column(String, unique=True)
    phone = Column(String, nullable=False)
    username = Column(String, unique=True)
    floater = Column (Boolean, nullable=False)
    week = Column(Integer, nullable=False)
    assigned = Column(String, nullable=False)

    roles = relationship('Role', secondary='volunteer_role',
                          back_populates='volunteers')
    schedules = relationship('Schedule', backref=backref('volunteer'))

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

&lt;/div&gt;



&lt;p&gt;Besides a primary key the volunteer table has two relational fields. &lt;strong&gt;&lt;em&gt;roles&lt;/em&gt;&lt;/strong&gt; is used for managing the relationship between the Role and Volunteer tables through the association table, &lt;strong&gt;&lt;em&gt;Volunteers_Role&lt;/em&gt;&lt;/strong&gt;. This is necessary because of the &lt;strong&gt;&lt;em&gt;many-to-many&lt;/em&gt;&lt;/strong&gt; relationship between Volunteer and Role. When dealing with a many-to-many relationship it is necessary to have an intermediary table to connect the two tables. &lt;strong&gt;&lt;em&gt;back_populates&lt;/em&gt;&lt;/strong&gt; is a relational parameter that tells sqlalchemy to link the volunteer table to the role table.&lt;/p&gt;

&lt;p&gt;Schedule has a &lt;strong&gt;&lt;em&gt;one-to-many&lt;/em&gt;&lt;/strong&gt; relationship with Volunteer so the &lt;strong&gt;&lt;em&gt;schedules&lt;/em&gt;&lt;/strong&gt; relational field is used to manage that relationship. &lt;/p&gt;

&lt;p&gt;fig(4)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zYNLb8r9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aryvnn8f66roowe4ikls.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zYNLb8r9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aryvnn8f66roowe4ikls.png" alt="volunteer_table" width="800" height="145"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Role
&lt;/h2&gt;

&lt;p&gt;fig(5)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Role(Base):
    __tablename__ = 'roles'

    id = Column(Integer, primary_key=True)
    position = Column(String, nullable=False)

    volunteers = relationship('Volunteer', secondary='volunteer_role',
                          back_populates='roles')
    schedules = relationship('Schedule', backref=backref('role'))

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

&lt;/div&gt;



&lt;p&gt;Like the Volunteer table the Role table has two relational fields. &lt;strong&gt;&lt;em&gt;volunteers&lt;/em&gt;&lt;/strong&gt; which manages the relatationship between Role and Volunteer through the association table &lt;strong&gt;&lt;em&gt;Volunteer_Role&lt;/em&gt;&lt;/strong&gt;. Also like the Volunteer table sqlalchemy uses the &lt;strong&gt;&lt;em&gt;back_populates&lt;/em&gt;&lt;/strong&gt; parameter to point roles back to &lt;strong&gt;&lt;em&gt;volunteers&lt;/em&gt;&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Also like the Volunteer table, &lt;strong&gt;&lt;em&gt;schedules&lt;/em&gt;&lt;/strong&gt; is used to manage the &lt;strong&gt;&lt;em&gt;one-to-many&lt;/em&gt;&lt;/strong&gt; relationship between Schedule and the Role tables.&lt;/p&gt;

&lt;p&gt;fig(6)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JMC2lq1f--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5778p7oehyc2224lzxxs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JMC2lq1f--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5778p7oehyc2224lzxxs.png" alt="role_table" width="445" height="176"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Volunter_Role
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;volunteer_role = Table (
     'volunteer_role',
     Base.metadata,
     Column('vol_id', ForeignKey('volunteers.id')),
     Column('role_id', ForeignKey('roles.id'))
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Because the volunteer_role table is the association table that manages the &lt;em&gt;many-to-many&lt;/em&gt; relationship between volunteers and roles you will see that some volunteers (vol_ids) are in the table more than once. You can also role_ids are in this table multiple times.&lt;/p&gt;

&lt;p&gt;So in the Volunteer table &lt;em&gt;back_populates&lt;/em&gt; links role back to volunteer and in the Role table &lt;em&gt;back_populate&lt;/em&gt; links volunteer to role. They have what we call a bi-directional relationship with each returning a collection of the other. &lt;/p&gt;

&lt;p&gt;fig(7)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--77YoRv8Y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmqmsexw9c43nxaj0nen.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--77YoRv8Y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmqmsexw9c43nxaj0nen.png" alt="volunteer_role" width="653" height="464"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Example: Many-to-Many&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
fig(8)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ipdb&amp;gt; volunteer.username
'Laura_Beltran'

ipdb&amp;gt; volunteer.roles
[Role id: 2, Position: usher , Role id: 4, Position: prayer ]
ipdb&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An instance of volunteer can have many roles. Notice volunteer is using the &lt;em&gt;roles&lt;/em&gt; relational attribute to list all the roles pertaining to the volunteer Lauar_Beltran.&lt;/p&gt;

&lt;p&gt;A role can have many volunteers&lt;br&gt;
fig(9)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ipdb&amp;gt; role.position
'greeter'
ipdb&amp;gt;
ipdb&amp;gt; [role.username for role in role.volunteers]
['Victoria_Romero', 'Samuel_Mcclain', 'Emily_Wallace', 'Rodney_Woods']
ipdb&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see an instance of role can return many volunteers. Notice role is using the &lt;em&gt;volunteers&lt;/em&gt; relational attribute to list all the volunteers who are prayers.&lt;/p&gt;

&lt;p&gt;Now that we see how the tables relate to each other, lets take a closer look at &lt;strong&gt;&lt;em&gt;The Scheduler&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Scheduler
&lt;/h2&gt;

&lt;p&gt;The Scheduler is a &lt;em&gt;Command Line Interface&lt;/em&gt; or CLI app, enabling the user to interact with it from the command line.  The cli file that envokes the scheduler is...&lt;em&gt;wait for it&lt;/em&gt;...&lt;strong&gt;scheduling.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;fig(10)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EKW6IopD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://gifdb.com/images/high/disappointed-face-boy-blink-g97pz8zfml7oypt1.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EKW6IopD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://gifdb.com/images/high/disappointed-face-boy-blink-g97pz8zfml7oypt1.gif" alt="disappointed" width="500" height="593"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ok, I can see you're not impressed, so lets take a look at what it does and see if we can change your mind!&lt;/p&gt;

&lt;p&gt;fig(11)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Kc9ga-SR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a11l38y4o6xxzniclr73.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Kc9ga-SR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a11l38y4o6xxzniclr73.png" alt="TheScheduler" width="473" height="256"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Because the The Scheduler is a cli the interface is very simple but effective. It begins with a menu that allows you to select the action you want to perform. &lt;/p&gt;
&lt;h2&gt;
  
  
  Add Volunteer
&lt;/h2&gt;

&lt;p&gt;fig(12)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rF3AecaD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4hndmanyh4nmr2t86n9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rF3AecaD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4hndmanyh4nmr2t86n9.png" alt="add_volunteer" width="549" height="427"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When the user selects Add Volunteer they are taken to the "Add Volunteer" screen where they are prompted to enter specific information about the volunteer. Notice at every prompt is the opportunity to quit the application by hitting x except the last prompt, that's because by then the user is most likely commited to the process. &lt;/p&gt;

&lt;p&gt;It finishes by displaying a message containing the user's full name, &lt;em&gt;username&lt;/em&gt; which is created internally, and the role they'll be serving in. The user then hits enter to exit and return to the menu.&lt;/p&gt;

&lt;p&gt;Notice Tom Cruise #41 in the volunteer database:&lt;/p&gt;

&lt;p&gt;fig(13)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VVEN-kEd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wienfzc6g6kdx2eub3q9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VVEN-kEd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wienfzc6g6kdx2eub3q9.png" alt="tom_database" width="800" height="58"&gt;&lt;/a&gt;&lt;br&gt;
The Scheduler uses the ORM (Object Relational Mapper), SQLAlchemy with Python to make this all happen. Now let's take a look at the code that makes up the Add Volunteer method.&lt;/p&gt;

&lt;p&gt;Note: The CLI code for this app is pretty big because of all the validation that takes place, so because of that I'm going to limit the code shown to just the sqlalchemy.&lt;/p&gt;

&lt;p&gt;With that said lets get to it!!!&lt;/p&gt;

&lt;p&gt;The CLI does the job of validating each attribute below. Once it's satisfied all the data entered is valid it calls the add_volunteer method. The usernamne is generated by putting an "_" between the first and last name. As you'll see later on the usernamne is used extensivley to identify the volunteer so it needs to be unique. Because the possibility of having more than one person with the same first and last name is very high, the add_volunteer method checks to see if it exist, if it does it appends a random interger between 1-50 to the username.&lt;/p&gt;

&lt;p&gt;fig(14)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_volunteer(fname, lname, email, phone, floater, week, position="prayer"):
            username = f"{fname}_{lname}"
            username_exist = session.query(Volunteer).filter(Volunteer.username == username).first()
            if username_exist:
                username = username + "_" + str(random.randint(1,50))  
            assigned = "No"  
            role = session.query(Role).filter(Role.position == position).first()
            volunteer = Volunteer(
                     first_name = fname, 
                     last_name = lname,
                     email = email,
                     phone = phone,
                     username = username,
                     floater = floater,
                     week = week,
                     assigned = assigned
            )
            session.add(volunteer)
            volunteer.roles.append(role)
            session.commit()
            return volunteer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;volunteer.roles.append(role)&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Using the relationship attributes on the volunteer and role tables the Volunteer_Role table is populated.&lt;/p&gt;
&lt;h2&gt;
  
  
  Delete Volunteer
&lt;/h2&gt;

&lt;p&gt;Tom Cruise has become very busy working on "Mission Impossible: Maverick" so we're going to remove him and give him the space he needs to film the movie.&lt;/p&gt;

&lt;p&gt;fig(15)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zbtmLgSa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x2qju7rqa8tk9m7wnii.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zbtmLgSa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x2qju7rqa8tk9m7wnii.png" alt="delete" width="458" height="274"&gt;&lt;/a&gt;&lt;br&gt;
As you can see Tom has been removed and free to persue his acting career.&lt;/p&gt;

&lt;p&gt;fig(16)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6ghmxjmA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fnch5p2ntpa5uuxxzfw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6ghmxjmA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fnch5p2ntpa5uuxxzfw.png" alt="tom_not_database" width="800" height="34"&gt;&lt;/a&gt;&lt;br&gt;
After all the validation is done the cli calls the delete_volunteer method.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Get Tom's information from the volunteer table,&lt;/li&gt;
&lt;li&gt;Tom role association is removed from Volunteer_Role&lt;/li&gt;
&lt;li&gt;if Tom is on the schedule that schedule instance is removed.&lt;/li&gt;
&lt;li&gt;Tom is removed from the volunteer table&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;fig(17)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def delete_volunteer(username):
        volunteer = session.query(Volunteer).filter(
                    Volunteer.username == username).first()

        # Delete Volunteer _Role association from volunteer_role table
        [volunteer.roles.remove(role) for role in volunteer.roles]

        # Delete volunteer from schedule
        if volunteer.schedules:
            [session.delete(schedule) for schedule in volunteer.schedules]

        # Delete Volunteer
        session.delete(volunteer)
        session.commit() 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;fig(18)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if volunteer.schedules:
            [session.delete(schedule) for schedule in volunteer.schedules]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fig(18) shows the one-to-many relationship between the volunteer and the schedule. The schedules side of the relationship produces a collection, in this case is a list, that's then iterated over to get the needed information.&lt;/p&gt;

&lt;h2&gt;
  
  
  Modify Volunteer
&lt;/h2&gt;

&lt;p&gt;Mary Spalding has just been married and wants to change her last name, email handle and role. &lt;/p&gt;

&lt;p&gt;What you see below is the purpose of the Volunteer_Role table. Mary's id is 44 and right now she's an usher and the usher id is 2. So the association table &lt;em&gt;(Volunteer_Role)&lt;/em&gt; is associating Mary's id with the usher id.&lt;/p&gt;

&lt;p&gt;fig(19)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WDIYhZkL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29n8l90qqlfejspaymf8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WDIYhZkL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29n8l90qqlfejspaymf8.png" alt="Mary_role" width="800" height="59"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;fig(20)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bxoT_zEU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1d18pg21n5hn0gvvefm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bxoT_zEU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1d18pg21n5hn0gvvefm.png" alt="modify" width="688" height="563"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here we see Mary stepping through the prompts. We her changing her last name to Spalding-Wilson and her email to &lt;a href="mailto:spalding-wilson@gmail.com"&gt;spalding-wilson@gmail.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;fig(21)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--r75Tz3ou--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2tp7ux94tawqr7xipj3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--r75Tz3ou--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2tp7ux94tawqr7xipj3.png" alt="show_role" width="635" height="202"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice Mary's current role as usher is listed. It's important to remember there is no foreign key for role.id in the Volunteer table. The Scheduler is able to list the usher in association with Mary because of the Volunteer_Role table and the relational parameters provided to both tables. &lt;/p&gt;

&lt;p&gt;fig(22)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tZPuqGND--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5cu4r2voxc7w5r1642u4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tZPuqGND--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5cu4r2voxc7w5r1642u4.png" alt="change_complete" width="625" height="271"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Scheduler is processing the changes and prints the message "Change was successful".  The user then hits enter to exit and return to the menu.&lt;/p&gt;

&lt;p&gt;Now let's take a look at the database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Volunteer_Role:&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Mary's role association has changed from 2 (usher) to 1 (greeter)&lt;/p&gt;

&lt;p&gt;fig(23)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oeNojchC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wf40h87h8ts0rs5rvoy3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oeNojchC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wf40h87h8ts0rs5rvoy3.png" alt="role_change" width="768" height="87"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Volunteer&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Mary's last name changed to Spalding-Wilson and her email changed to &lt;a href="mailto:spalding_wilson@gmail.com"&gt;spalding_wilson@gmail.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;fig(24)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Nf_xP-QQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cf692b9emyq381rqxb8n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Nf_xP-QQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cf692b9emyq381rqxb8n.png" alt="email_change" width="800" height="57"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;All the changes have been persisted to the database!&lt;/p&gt;

&lt;p&gt;fig(25)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--O0gXUC44--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://media.tenor.com/z0LqkOW9fooAAAAM/carlton-dance-ya.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--O0gXUC44--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://media.tenor.com/z0LqkOW9fooAAAAM/carlton-dance-ya.gif" alt="carlton_dance" width="220" height="165"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Ahem...the code...&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;During the validation phase the cli collects all the validate information into an object called changes using "role" as the key and "value" as the value. The object is then passed to the modify_volunteer method along with the usernamne. Using the items() object method, it's loop through changing the information based on the role passed in. If the role is being changed then we have to modify the Volunteer_Role table by removing the association to the old role and adding an association to the new role. This is how we're able to see the role changed from 2 to 1 in the fig(19) and fig(23) above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; def modify_volunteer(username, changes):
        volunteer=session.query(Volunteer).filter(Volunteer.username == username).first()
        for key,value in changes.items():
            if key == "role":
               role = session.query(Role).filter(Role.position == value).first()
               volunteer.roles.append(role)
            if key == 'old':
               for role in volunteer.roles:
                   if role.position == value:
                      volunteer.roles.remove(role)
            setattr(volunteer,key,value)
        session.commit()
        return volunteer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Add to Schedule
&lt;/h2&gt;

&lt;p&gt;Let's add Mary to the schedule.   &lt;/p&gt;

&lt;p&gt;fig(26)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--889muYmz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3uk17vrq0ia5bsltotlc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--889muYmz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3uk17vrq0ia5bsltotlc.png" alt="add_mistake" width="800" height="457"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hmmm... looks like someone forgot Mary is not longer an usher . Remember she changed her role to greeter &lt;em&gt;fig(23)&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;fig(27)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wpbUm7WL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n379qa8gbyny3l79sisu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wpbUm7WL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n379qa8gbyny3l79sisu.png" alt="add_schedule_complete" width="800" height="618"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Mary Spalding has been successfully added to the schedule.&lt;br&gt;
Let's check the Schedule table to make sure change was persisted to the database&lt;/p&gt;

&lt;p&gt;fig(28)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JkVaEVS_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ypcocj20rshlw2krwya6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JkVaEVS_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ypcocj20rshlw2krwya6.png" alt="change_schedule" width="800" height="59"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Remember the Schedule contains two foreign keys; one for Role and one for Volunteer &lt;em&gt;fig(2)&lt;/em&gt;. Mary's id, 44 and the role id for greeter which is 1. We see the date is the date entered, 2023-09-03.&lt;/p&gt;

&lt;p&gt;CLI validates information entered by user and then passes it to the add_to_schedule method. The datetime.strptim method is used to convert the date to a python format. The method get an instance of th volunteer and role and useed them to create an instance of a schedule thats then added to the schedule table.&lt;/p&gt;

&lt;p&gt;fig(29)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add_to_schedule(username,position,input_date):

        schedule_date = datetime.strptime(input_date, '%Y-%m-%d').date()

        volunteer = session.query(Volunteer).filter(Volunteer.username == username).one()
        role = session.query(Role).filter(Role.position == position).one()

        schedule = Schedule(
            date = schedule_date,
            vol_id = volunteer.id,
            role_id = role.id
        )
        volunteer.assigned = "Yes"
        session.commit()
        session.add(schedule)
        session.commit()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Modify Schedule
&lt;/h2&gt;

&lt;p&gt;Mary has decided she will not be in church on Sep 3 so she'll need to change the date.&lt;/p&gt;

&lt;p&gt;fig(30)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Z492jbUq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3rz45gnd98py7usqwvjk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Z492jbUq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3rz45gnd98py7usqwvjk.png" alt="modify_schedule" width="800" height="711"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now let's check the Schedule to make sure the date has been changed.&lt;/p&gt;

&lt;p&gt;fig(31)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w-l0qBX_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o8geu7727ni5ky2hsrz3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w-l0qBX_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o8geu7727ni5ky2hsrz3.png" alt="date_change" width="800" height="60"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yes! The date was changed from 2023-09-03 to 2023-09-10.&lt;br&gt;
&lt;strong&gt;Make note of the shedule id 54&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Once again CLI validation is complete and informaion is passed to the modify_schedule. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;date is converted to python&lt;/li&gt;
&lt;li&gt;get an instance of the role passed in&lt;/li&gt;
&lt;li&gt;get an instance of the volunteer passed in&lt;/li&gt;
&lt;li&gt;filter on the above information we get an schedule object &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Just like we did for modify_volunteer we use the object changes to store the "change data" in key value pairs. Using a for loop we interate over the object using the items() method to seperate the key value pairs. Changes are made based on the key and value stored.&lt;/p&gt;

&lt;p&gt;fig(32)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def modify_schedule(username, input_date, role, changes):

        schedule_date = datetime.strptime(input_date, '%Y-%m-%d').date()
        role = session.query(Role).filter(Role.position == role).first()
        volunteer=session.query(Volunteer).filter(Volunteer.username == username).first()

        schedule = session.query(Schedule).filter(Schedule.vol_id == volunteer.id,
               Schedule.date == schedule_date, Schedule.role_id == role.id).first()

        for key,value in changes.items():
            if key == "username":
               user = session.query(Volunteer).filter(Volunteer.username == value ).first()
               print(green(f'\nchanging username from {username} to {value}...\n')) 
               schedule.vol_id=user.id
            elif key == "role":
                new_role = session.query(Role).filter(Role.position == value ).first()
                print(green(f'\nchanging role from {role.position} to {new_role.position}...\n')) 
                schedule.role_id=new_role.id
            else:
                new_date = datetime.strptime(value,'%Y-%m-%d').date()
                print(green(f'\nchanging date from {schedule_date} to {new_date}...\n')) 
                schedule.date=new_date   
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Delete Schedule
&lt;/h2&gt;

&lt;p&gt;Mary decided she wants to be removed from the schedule for that day.  &lt;/p&gt;

&lt;p&gt;fig(33)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NvBzR78N--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75ytlpif6zhbj3g9tqgt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NvBzR78N--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75ytlpif6zhbj3g9tqgt.png" alt="wrong_date" width="800" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Someone forgot Mary had previously changed her date from Sept 3 to Sept 10. fig(31)&lt;/p&gt;

&lt;p&gt;fig(34)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GpGCxV_E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/amy1mrwaw5iyo52nnrlz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GpGCxV_E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/amy1mrwaw5iyo52nnrlz.png" alt="correct_date" width="800" height="601"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Schedule was removed for Mary for Sep 10, 2023.&lt;/p&gt;

&lt;p&gt;fig(35)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--yLc37RDw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lmojp33d50gicylp65sp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--yLc37RDw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lmojp33d50gicylp65sp.png" alt="schedule_gone" width="800" height="58"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice the schedule id &lt;em&gt;54&lt;/em&gt; has been removede from the schedule table. &lt;/p&gt;

&lt;p&gt;As my husband likes to say...&lt;em&gt;Good Stuff!!!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You see the CLI validation at work in fig(33). The CLI first checked to see if Mary had a schedule for that date. Using a list comprehension we look over the list produced by volunteer.schedules checking the date and removing it when we find a match. Because a volunteer can have more than one schedule we check to see if this is the &lt;strong&gt;&lt;em&gt;only&lt;/em&gt;&lt;/strong&gt; schedule by checking the size of the list. If the size = 1 then we know thats the only schedule and we can change the volunteer's assigned status to "No". &lt;/p&gt;

&lt;p&gt;fig(36)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def delete_schedule(username, input_date):
        schedule_date = datetime.strptime(input_date, '%Y-%m-%d').date()
        volunteer = session.query(Volunteer).filter(Volunteer.username == username).first()
        [session.delete(schedule) for schedule in volunteer.schedules if schedule.date == schedule_date]
        if(len(volunteer.schedules) == 1 ):
            volunteer.assigned = "No"
        print(f"Removing {volunteer.first_name} {volunteer.last_name} from the schedule for {input_date}... ")
        session.commit()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;## Query Schedule by Date&lt;/p&gt;

&lt;p&gt;Let's see if anyone else is scheduled for Sep 10, 2023:&lt;/p&gt;

&lt;p&gt;fig(37)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Rdek5gI2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xkinkow9iw50ol62d075.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Rdek5gI2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xkinkow9iw50ol62d075.png" alt="by_date_empty" width="800" height="466"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After validation the date is passed into query_by_date(). The date is pythonized &lt;em&gt;(I'm sure that's not a word)&lt;/em&gt;. We get a list of all the schedules that match that date.  If the list size == 0 then we know there are no schedules for that date else we loop through the list creating a volunteer and role object for each schedule in the list and print them out.&lt;/p&gt;

&lt;p&gt;fig(38)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    def query_by_date(input_date):
        schedule_date = datetime.strptime(input_date, '%Y-%m-%d').date()
        schedules = session.query(Schedule).filter(Schedule.date == schedule_date).all()

        if len(schedules) == 0:
            print (red(f"\nSchedule date: {input_date}\n"))
            print (red("&amp;lt;---No schedule---&amp;gt;"))
        else:  
            print (green(f"\nSchedule date: {input_date}\n"))  
            for schedule in schedules:
                volunteer = session.query(Volunteer).filter(Volunteer.id == schedule.vol_id).first()
                role = session.query(Role).filter(Role.id == schedule.role_id).first()
                print (green(f"{volunteer.first_name} {volunteer.last_name}: {role.position}"))

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

&lt;/div&gt;



&lt;p&gt;Let's use a date that actually has somone scheduled:&lt;/p&gt;

&lt;p&gt;fig(39)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UH3NWTW9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j7bm4ljt5pnf1j3jc1a2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UH3NWTW9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j7bm4ljt5pnf1j3jc1a2.png" alt="by_date_good" width="800" height="509"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Query Schedule by Name
&lt;/h2&gt;

&lt;p&gt;Now let see if Mary is on the schedule&lt;/p&gt;

&lt;p&gt;fig(40)&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5xiWarfu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dcntg0x1pvp96b7zhevk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5xiWarfu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dcntg0x1pvp96b7zhevk.png" alt="Mary_not" width="800" height="667"&gt;&lt;/a&gt;&lt;br&gt;
Oops! I misspelled her name but the app allowed me to re-enter. As we see Mary does is not on the schedule at all.&lt;/p&gt;

&lt;p&gt;Again we see CLI validation at work. I misspelled her name and the CLI caught by checking if the user existed.&lt;/p&gt;

&lt;p&gt;Lets see if Kara Rivera is scheduled to serve:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--L2H2CjKg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndtmwb7rdwvnv0kxokfq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--L2H2CjKg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndtmwb7rdwvnv0kxokfq.png" alt="Kara_good" width="800" height="566"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here the one-to-many relationship is clearly seen between the volunteer and the schedule and the role and the schedule . Kara is serving in multiple roles on multiple dates. &lt;/p&gt;

&lt;p&gt;We saw the CLI doing it job validating the information enter in fig(40). We create an object for the username and an object for all volunteers. If the volunteer is not assigned, no need to go any further and we print the full name and the message "No schedule" else let's see if I remember what I did here and why:&lt;br&gt;
for each schedule in the list of schedules for the username were going to &lt;br&gt;
   going loop through the roles to see if the role_id matchs the schedule.role_id&lt;br&gt;
    Then we check if there is a swappout_id (I'll get to that)&lt;br&gt;
      if there is a swappout_id were going to loop through all the volunteers to get the name that matches the swappout.id and print that information out with swappout information&lt;br&gt;
      if no swappout_id print without the swappout information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def query_by_name(username):
        volunteer = session.query(Volunteer).filter(Volunteer.username == username).first()  
        volunteers = session.query(Volunteer).all()
        roles = session.query(Role).all()

        if volunteer.assigned == "No":
            print(red(f"\n{volunteer.first_name} {volunteer.last_name} \n"))
            print (red("&amp;lt;---No schedule---&amp;gt;"))
        else:
            print(green(f"\n{volunteer.first_name} {volunteer.last_name} \n"))
            for schedule in volunteer.schedules:
                for role in roles:
                    if role.id == schedule.role_id:
                        if schedule.swappout_id:
                            for vol in volunteers:
                                if vol.id == schedule.swappout_id:
                                    print(schedule.date.strftime("%B %d, %Y"),":" + role.position, "&amp;lt;" + vol.username + "&amp;gt;")
                        else:
                            print(schedule.date.strftime("%B %d, %Y"), ":" + role.position)  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Swap&lt;/strong&gt; - Notice the schedule has a swapp_id field.  Sometimes volunteers swap dates. For historical purposes swapp0ut_id holds the id of the volunteer who was swapped out. &lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/p6XZqRYZSyA"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h3&gt;
  
  
  Giselle Smith
&lt;/h3&gt;

&lt;p&gt;Giselle is a Software Development Engineer FullStack studying at &lt;a href="https://flatironschool.com/"&gt;FlatIron School&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Resources:&lt;br&gt;
Disappointed Face: &lt;a href="https://gifdb.com/gif/disappointed-face-boy-blink-g97pz8zfml7oypt1.html"&gt;https://gifdb.com/gif/disappointed-face-boy-blink-g97pz8zfml7oypt1.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Carlton Dance: &lt;a href="https://tenor.com/view/carlton-dance-ya-yes-fresh-prince-of-bel-air-carlton-banks-gif-17061920"&gt;https://tenor.com/view/carlton-dance-ya-yes-fresh-prince-of-bel-air-carlton-banks-gif-17061920&lt;/a&gt;&lt;/p&gt;

</description>
      <category>sqlalchemy</category>
      <category>relational</category>
      <category>python</category>
      <category>sqlite</category>
    </item>
    <item>
      <title>useContext</title>
      <dc:creator>gisellec60</dc:creator>
      <pubDate>Sun, 02 Jul 2023 23:00:40 +0000</pubDate>
      <link>https://dev.to/gisellec60/usecontext-53d4</link>
      <guid>https://dev.to/gisellec60/usecontext-53d4</guid>
      <description>&lt;p&gt;What is &lt;strong&gt;&lt;em&gt;useContext&lt;/em&gt;&lt;/strong&gt; and how do we use it. &lt;/p&gt;

&lt;p&gt;I'll have to admit, I  have a selfish reason for writing this blog on useContext...it's so I can understand how to use it because I have a feeling I'll need it for my next project.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;useContext&lt;/em&gt; is another popular hook in react that allows data to be managed globally. It provides the ability to share data through a tree of nested components without passing it manually... &lt;em&gt;a process known as prop drilling&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Let me explain...&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Let's say we have a parent and 3 child components and state is set in the parent component. Inorder for child #3 to have access to a value in state set by its parent it would have to be passed down through props to child #1, and child #2 to get to child #3.&lt;br&gt;
&lt;/p&gt;

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

export default function Parent() {

const [fruit, setFruit] = useState("apple")   

return (
  &amp;lt;div&amp;gt;
  &amp;lt;p className="para"&amp;gt; 
     The Parent would love to have an {fruit}
     and give one to Child3. So the Parent will have to pass the    
     fruit to Child1fruit to Child1 who will pass it to Child2 
     who will pass it to Child3 so that Child3 can enjoy the 
     fruit.
  &amp;lt;/p&amp;gt; 
     &amp;lt;Child1 fruit={fruit} /&amp;gt;
 &amp;lt;/div&amp;gt;    

  );
}                                                                          

function Child1 ({fruit}) {
    return (
      &amp;lt;div&amp;gt; 
        &amp;lt;p className="para"&amp;gt;fruit passed to Child2  &amp;lt;/p&amp;gt; 
        &amp;lt;Child2 fruit={fruit} /&amp;gt;
     &amp;lt;/div&amp;gt; 
   )
}

function Child2 ({fruit}) {
  return(
    &amp;lt;div&amp;gt;
       &amp;lt;p className="para"&amp;gt;fruit passed to Child3  &amp;lt;/p&amp;gt; 
       &amp;lt;Child3 fruit={fruit} /&amp;gt;
    &amp;lt;/div&amp;gt;
  ) 
}

function Child3 ({fruit}) {
  return 
   &amp;lt;p className="para"&amp;gt; Child3 can now enjoy the {fruit}! &amp;lt;/p&amp;gt;
}  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OSTP8eaf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69yzkovld8eormx1mv53.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OSTP8eaf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69yzkovld8eormx1mv53.png" alt="Output" width="800" height="165"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice the Parent component passes fruit down to Child1 which inturn passes fruit down to Child2 which passes fruit down to Child3, without ever using it. This is the only way the Parent component can get fruit to the Child3 component. This process of passing data down through an heirachy is called &lt;strong&gt;&lt;em&gt;prop drilling&lt;/em&gt;&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;This may not look like much of a problem right now, but imagine you have an application with a heirarchy of nested compoenents that runs deep and is complex. Managing such an application can become confusing and hard to maintain. React's answer to this problem is to &lt;em&gt;create context&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;Let's redo our example above using the &lt;strong&gt;&lt;em&gt;useContext&lt;/em&gt;&lt;/strong&gt; hook:&lt;br&gt;
&lt;/p&gt;

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

const FruitContext = createContext("")

export default function Parent() {

  const [fruit, setFruit] = useState("apple")   

  return (
     &amp;lt;div&amp;gt;
        &amp;lt;p className="para"&amp;gt; 
        The Parent would love to have an {fruit} and give one to Child3 without
        going through Child1 and Child2. 
        &amp;lt;/p&amp;gt; 
        &amp;lt;FruitContext.Provider value={fruit}&amp;gt; 
           &amp;lt;Child1  /&amp;gt; 
        &amp;lt;/FruitContext.Provider&amp;gt;
     &amp;lt;/div&amp;gt;    

  );
}
 function Child1 () {
    return (
        &amp;lt;div&amp;gt; 
            &amp;lt;p className="para"&amp;gt;Skip Child1  &amp;lt;/p&amp;gt; 
            &amp;lt;Child2  /&amp;gt;

        &amp;lt;/div&amp;gt; 
      )
}
function Child2 () {
  return(
    &amp;lt;div&amp;gt;
       &amp;lt;p className="para"&amp;gt;Skip Childl2  &amp;lt;/p&amp;gt; 
       &amp;lt;Child3 /&amp;gt;

    &amp;lt;/div&amp;gt;
  ) 
}

function Child3 () {
  const fruit = useContext(FruitContext);
  return &amp;lt;p className="para"&amp;gt; Child3 can now enjoy the {fruit}! &amp;lt;/p&amp;gt;
}  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_feyG2iT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d2fnfnewn7ickm6iebip.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_feyG2iT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d2fnfnewn7ickm6iebip.png" alt="Output" width="796" height="154"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see Child3 has access to fruit without it ever being passed down through the heirarchy of components. Instead of passing fruit down as a prop through the tree, Child3 was able to access fruit by the use of &lt;em&gt;useContext&lt;/em&gt;,&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;A closer look...&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Step1 - We create the context object.  In the case above the context object is &lt;em&gt;FruitContext&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;const FruitContext = createContext("")&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Step2 - The context object had a property called the &lt;em&gt;Provider&lt;/em&gt; and the provider takes a value which in this case is the state variable fruit. The provider is wrapped around the component at the top of the tree so that every component in the tree from that point on has access to context object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; export default function Parent() {
     const [fruit, setFruit] = useState("apple")
     return (
     &amp;lt;div&amp;gt;
        &amp;lt;p className="para"&amp;gt; 
         The Parent would love to have an {fruit} and give one to 
         Child3 withoutgoing through Child1 and Child2. 
        &amp;lt;/p&amp;gt; 
        &amp;lt;FruitContext.Provider value={fruit}&amp;gt; 
           &amp;lt;Child1  /&amp;gt; 
        &amp;lt;/FruitContext.Provider&amp;gt;
     &amp;lt;/div&amp;gt;    

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

&lt;/div&gt;



&lt;p&gt;I made the statement, &lt;em&gt;The provider is wrapped around the component at the top of the tree so that every component in the tree **from that point on has access to context object.&lt;/em&gt;** That's because any component not in the &lt;strong&gt;wrapper&lt;/strong&gt;  does not have access to context provider.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Example:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function Parent() {
     const [fruit, setFruit] = useState("apple")
     return (
         &amp;lt;ChildA fruit={fruit}  /&amp;gt;
         &amp;lt;FruitContext.Provider value={fruit}&amp;gt; 
            &amp;lt;p&amp;gt; The Parent would love to have an {fruit} &amp;lt;/p&amp;gt; 
            &amp;lt;Child1 /&amp;gt;
         &amp;lt;/FruitContext.Provider&amp;gt;
    )
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above the ChildA component does not have access to FruitContext. So for ChildA and its &lt;em&gt;children&lt;/em&gt; to have access to the state variable fruit it will have to be manually passed down through props. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Ok, moving along...&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Step3 - We then use the useContext() hook to gain access to the 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;function Child3() {
  const fruit = useContext(FruitContext);
  return &amp;lt;p&amp;gt; fruit prop not passed to Child3 but Child3 has the {fruit} now! &amp;lt;/p&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Imagine...&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
You have a component tree that runs 26 components deep(ChildA-ChildZ) and during development you decide that the Parent and ChildZ need to share a state varaible. Without creating context you would have to manually pass the state variable through each component starting at ChildA down through ChildZ. That's 26 levels deep for those of us counting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function Parent() {
     const [fruit, setFruit] = useState("apple")
      return (
         &amp;lt;p&amp;gt; The Parent would love to have an {fruit} &amp;lt;/p&amp;gt; 
         &amp;lt;ChildA fruit={fruit}/&amp;gt;
     )  
 }

// Components ChildB({fruit})-ChildY({fruit}) 

function ChildZ({fruit}) {
   return &amp;lt;p&amp;gt;ChildZ has the {fruit} now! &amp;lt;/p&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, by creating context you would:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;import the useContext and createContext hook&lt;/li&gt;
&lt;li&gt;create the context object&lt;/li&gt;
&lt;li&gt;wrap CHildA in the context provider&lt;/li&gt;
&lt;li&gt;Skip to ChildZ and give it access to fruit via useContext(ContextProvider)
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import ({useContext, createContext, useState}) from "react"
const FruitContext = createContext("")
export default function Parent() {
     const [fruit, setFruit] = useState("apple")
     return (
          &amp;lt;FruitContext.Provider value=(fruit)&amp;gt;
            &amp;lt;ChildA/&amp;gt;
          &amp;lt;FruitContext.Provider&amp;gt;  
    )  
 }
// Skip Components ChildB-ChildY 
...
function ChildZ() {
  const fruit = useContext(FruitContext);
  return &amp;lt;p&amp;gt;ChildZ has the {fruit} now! &amp;lt;/p&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the case above we can easily see how ineffficient prop drilling would be in passing fruit down a deeply nested hierarchy of components. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;NOTE:&lt;/em&gt;&lt;/strong&gt; Something to make note of is when a context value changes the calling component will re-render. If rendering becomes expensive there is a possible solution called &lt;strong&gt;&lt;em&gt;memo&lt;/em&gt;&lt;/strong&gt;. A component re-renders whenever it parent re-renders &lt;em&gt;even if its props have not changed&lt;/em&gt;. Memo allows you to create a component that will not re-render when the parent re-renders &lt;strong&gt;&lt;em&gt;as long as its props have not changed&lt;/em&gt;&lt;/strong&gt;. The component in the case is said to have been "memoized". This process will help with optimization by cutting down on unneccessary rendering. Click &lt;a href="https://react.dev/reference/react/memo"&gt;here&lt;/a&gt; for more information. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The useContext Hook solves the problem of prop drilling down a deeply nested tree of components&lt;/li&gt;
&lt;li&gt;To use the useContext hook you have to first import both useContext and createContext from react.&lt;/li&gt;
&lt;li&gt;createContext creates a context "Provider" that takes a value.
&lt;/li&gt;
&lt;li&gt;The context provider is wrapped around the top level component and every component down the tree has access to the value provided by the context provider.&lt;/li&gt;
&lt;li&gt;useContext is how a child component gets access to the actual data in the context provider.&lt;/li&gt;
&lt;li&gt;If rendering becomes expensive memo may be a solution. &lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>hooks</category>
      <category>react</category>
      <category>usestate</category>
      <category>usecontext</category>
    </item>
    <item>
      <title>So,What is "this"?</title>
      <dc:creator>gisellec60</dc:creator>
      <pubDate>Wed, 10 May 2023 20:14:07 +0000</pubDate>
      <link>https://dev.to/gisellec60/sowhat-is-this-o6i</link>
      <guid>https://dev.to/gisellec60/sowhat-is-this-o6i</guid>
      <description>&lt;h1&gt;
  
  
  This
&lt;/h1&gt;

&lt;p&gt;In short &lt;em&gt;&lt;strong&gt;this&lt;/strong&gt;&lt;/em&gt; is a special object created by and used in the global/window or function execution context....&lt;em&gt;what???&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;Execution context??? Yeah I know..., I hate when someone introduces a term or concept without explaining what it is and how it relates to the current topic, so I'm going to take a little time to explain "&lt;strong&gt;&lt;em&gt;execution context&lt;/em&gt;&lt;/strong&gt;", before discussing the &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; keyword.  &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is an "execution context"?&lt;/strong&gt;&lt;br&gt;
When JavaScript begins it creates an environment called the "execution context". The execution context is responsible for transforming and executing code. &lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;&lt;em&gt;global&lt;/em&gt;&lt;/strong&gt; execution context is created when a JavaScript script starts to run, and represents the global scope. A &lt;strong&gt;&lt;em&gt;function&lt;/em&gt;&lt;/strong&gt; execution context is created when a function is called, and represents the function's local scope.&lt;/p&gt;

&lt;p&gt;The execution context is made up of two phases: creation and execution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Creation:&lt;/em&gt;&lt;/strong&gt; This is when the execution context is created and the environment is setup. Variable and functions values are determined along with the scope chain for the execution context. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Execution:&lt;/em&gt;&lt;/strong&gt; This phase is where the code is executed. This is where function calls are evaluated along with any statements or expressions.&lt;/p&gt;

&lt;p&gt;Okay, so now that we got that out of the way... what does execution context have to do with "&lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt;"?&lt;/p&gt;

&lt;p&gt;Well, I'm glad you &lt;em&gt;asked&lt;/em&gt;...&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; keyword represents the object that is executing the current piece of code. Remember we said a global execution context is created when JavaScript first runs? Well, during that time a special object called "&lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt;" is also created and is bonded to the global/window object. Likewise, when a function is invoked the function's execution context is created along with the  &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; keyword which is bonded to the object executing the code in the function. &lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name.f() =&amp;gt;  this.f()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; represents the object which in this case is "name", executing the function. &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; always represents the object to the left of the dot.&lt;/p&gt;

&lt;p&gt;The value of "&lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt;" depends on the context in which it appears: global, function, or class. Let's take a closer look at &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; and the different contexts in which it can be used.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Regular Function&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
In a regular function (&lt;em&gt;A function this is not the property of an object&lt;/em&gt;), &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; is not associated with an object so it evaluates to the window object using the browser and a global object when using node.js.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function show() {
    console.log(this === global);
}
console.log(show())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;node.js: global context&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F92yht5ocfecac5u6oyfc.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%2F92yht5ocfecac5u6oyfc.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;chrome browser: window context&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F51fsk3rx74r99bkjqblb.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%2F51fsk3rx74r99bkjqblb.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2&lt;/strong&gt;. &lt;strong&gt;&lt;em&gt;Functions as Property of an Object&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
When a function is called as the property of an object, the execution context is created along with the special object called &lt;strong&gt;_this _&lt;/strong&gt; which represents the object that owns 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;const school = {
    level: "High School",
    city:  "Bronx",
    getLevel: function () {
          return this.level
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; object in getLevel() function represents the school object. &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%2Fpid2xzgexzu2pt4dr7c6.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%2Fpid2xzgexzu2pt4dr7c6.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's take another look at this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const school = {
    level: "High School",
    city:  "Bronx",
    getLevel: function () {
          return console.log(`I went to ${this.level}school, in the ${this.city}`)
    }
}
console.log(school.getLevel())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmol3bljwgkkrbqlizu91.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%2Fmol3bljwgkkrbqlizu91.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice the code below and the code above both give the same results. You can also see that "&lt;strong&gt;this&lt;/strong&gt;" in the code above represents "&lt;strong&gt;school&lt;/strong&gt;" below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const school = {
    level: "High School",
    city:  "Bronx",
    getLevel: function () {
          return console.log(`I went to ${school.level}, in the ${school.city}`)
    }
}
console.log(school.getLevel())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F969ngssnbbzlzirflplh.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%2F969ngssnbbzlzirflplh.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Remember&lt;/em&gt;&lt;/strong&gt;, when you call a function expression that's a property of an object, that function expression's &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; object is the object on which the function is called i.e., the object to the left of the dot.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Constructor&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
When you use the &lt;strong&gt;&lt;em&gt;new&lt;/em&gt;&lt;/strong&gt; keyword to create an instance of a function object, you use the function as a constructor.  The following example declares a school function, then invokes it as a constructor:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function school(level) {
   this.level = level
} 
school.prototype.getLevel = function () {
   return this.level
}

let myschool = new school('Elementary School')
console.log(myschool.getLevel())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fagknge3165qca9hig55e.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%2Fagknge3165qca9hig55e.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
The expression new school('Elementary School') is a constructor invocation of the school function. JavaScript creates a new object and sets &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; to the newly created object. This pattern works great with only one potential problem. Now you can invoke the school() as a function or as a constructor. If you omit the new keyword as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let secondary = school("secondary")
console.log(secondary.level)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxxh72hi8nuax16cfjt2c.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%2Fxxh72hi8nuax16cfjt2c.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
The value in the school() sets the global object, the secondary.level returns undefined.  However to make sure school() is always invoked using constructor invocation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function school(level){
   if(!(this instanceof school)){
      throw Error ("must use the new operator to call the function")
   }
   this.level = level
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;ES6 introduced a new property called "&lt;strong&gt;&lt;em&gt;new.target&lt;/em&gt;&lt;/strong&gt;" that allows you to detect whether a function is called as a simple invocation or as a constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function school(level){
   if(!(new.target)){
      throw Error ("must use the new operator to call the function")
   }
   this.level = level
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmdph3g4wmo06ta2k5nil.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%2Fmdph3g4wmo06ta2k5nil.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Explicit&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
There are three ways to override the default context object when calling a function: "call" "apply" and "bind".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;call()&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getName(prefix) {
  console.log(prefix + this.name)
}
let stevenson = {
    name:"Stevenson"
}
let monroe ={
    name: "Monroe"
}
getName.call(monroe, "My school is ")
getName.call(stevenson, "My school is ")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmpvnll3ax7wlp5c4aj7r.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%2Fmpvnll3ax7wlp5c4aj7r.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;)&lt;br&gt;
In this example, we called the getName() indirectly using the call() method of the getName function. We passed stevenson and monroe objects as the first arguments of the call() method. The first argument is referred to as the &lt;strong&gt;&lt;em&gt;thisArg&lt;/em&gt;&lt;/strong&gt; object which are bonded to &lt;strong&gt;_this _&lt;/strong&gt; inside the function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;apply()&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;*&lt;em&gt;The apply() method is similar to the call() method in that it also requires a *&lt;/em&gt;_thisArg&lt;/em&gt;** object to be the first paramenter. Again,  &lt;strong&gt;&lt;em&gt;thisArg&lt;/em&gt;&lt;/strong&gt; object is bonded to the &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; keyword inside the function. The only difference between call() and apply() is the second argument passed to apply() is an array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getName.apply(monroe, ["My school is"])
getName.apply(stevenson, ["My school is"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd3qzxdu4jckxh33nx9wu.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%2Fd3qzxdu4jckxh33nx9wu.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;bind()&lt;/em&gt;&lt;/strong&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 school = {
    level: "High School",
    city:  "Bronx",
    getLevel: function () {
          return console.log(`I went to ${school.level}, in the ${school.city}`)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now a function expression is a property of an object which is a value that can be stored in a variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let level = school.getLevel;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We then call the method using the variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(level())

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

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc5tfgmuw7pecykbxvrif.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%2Fc5tfgmuw7pecykbxvrif.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice we get undefined instead of the level and city. That's because when you call a function expression without specifying its object, JavaScript sets this to the global object in non-strict mode and undefined in the strict mode. To fix this problem we use the bind() method. The bind() method creates a new function whose &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; keyword is set to a specified value. We also use a "&lt;strong&gt;&lt;em&gt;thisArg&lt;/em&gt;&lt;/strong&gt;" object as the first argument, which becomes the &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; inside 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;let level = school.getLevel.bind(school) 
console.log(level())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs7ekhco2c8361rhq67qi.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%2Fs7ekhco2c8361rhq67qi.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
In school.getLevel.bind(&lt;strong&gt;&lt;em&gt;school&lt;/em&gt;&lt;/strong&gt;), school is represents  &lt;strong&gt;&lt;em&gt;thisArg&lt;/em&gt;&lt;/strong&gt;.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;Note:&lt;/em&gt;&lt;/strong&gt; Whatever object you bind the variable to it will use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let school ={
   level: "High School",
   city: "Bronx",
   getLevel: function () {return (`I went to ${this.level}, in the ${this.city}`)
    }
}

let college ={
    level: "college",
    city: "Atlanta"
}
let level = school.getLevel.bind(college)
console.log(level())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fefs31db9tvgju5sa2kxj.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%2Fefs31db9tvgju5sa2kxj.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
So we bonded &lt;em&gt;&lt;strong&gt;school.getLevel.bind&lt;/strong&gt;&lt;/em&gt; to the college object. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5.&lt;/strong&gt; &lt;strong&gt;&lt;em&gt;Arrow Functions&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Arrow functions do not create their own execution context but inherits the &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; from the outer function where the arrow function is defined.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let getThis = () =&amp;gt; this;
console.log(getThis() === global)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F44sboxlpbhyrj6n3r07e.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%2F44sboxlpbhyrj6n3r07e.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
The arrow function does not create its own execution content. Remember regular functions when invoked create an execution context that also creates the &lt;strong&gt;_this _&lt;/strong&gt;object. Because of this defining a method using an arrow function will cause a problem:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Car() {
   this.speed = 120
}
Car.prototype.getSpeed = () =&amp;gt; {
   return this.speed
}
let car = new Car();
console.log(car.getSpeed());

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

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fteq7zwz7mntohnsji2e7.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%2Fteq7zwz7mntohnsji2e7.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Conclusion:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Execution Context is responsible for transforming code&lt;/li&gt;
&lt;li&gt; There are two phases to the execution context: Creation and Execution&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;&lt;em&gt;This&lt;/em&gt;&lt;/strong&gt; keyword is a special object created during the execution context creation. &lt;strong&gt;&lt;em&gt;This&lt;/em&gt;&lt;/strong&gt; can represents either the object executing the function, the global object or window object.&lt;/li&gt;
&lt;li&gt;The context object can be explicitly set by invoking &lt;strong&gt;&lt;em&gt;"call"&lt;/em&gt;&lt;/strong&gt; on a function and passing it &lt;strong&gt;_thisArg _&lt;/strong&gt;as the first argument. This allows for the object to be accessed using &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt;  from inside the function.&lt;/li&gt;
&lt;li&gt;The context object can also be explicitly set by invoking &lt;strong&gt;&lt;em&gt;"apply"&lt;/em&gt;&lt;/strong&gt; on the function and passing &lt;strong&gt;&lt;em&gt;thisArg&lt;/em&gt;&lt;/strong&gt; as the first argument allowing for the object to be accessed using &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; from inside the function.&lt;/li&gt;
&lt;li&gt;The context object can be bonded to a function using the "&lt;strong&gt;&lt;em&gt;bind&lt;/em&gt;&lt;/strong&gt;" method on the function and passing it &lt;strong&gt;&lt;em&gt;thisArg.&lt;/em&gt;&lt;/strong&gt; The bind method makes a copy of the function whose &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; keyword is bonded to a specified object.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>this</category>
      <category>javascript</category>
      <category>execution</category>
      <category>context</category>
    </item>
  </channel>
</rss>
