<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Reese Marshall on Medium]]></title>
        <description><![CDATA[Stories by Reese Marshall on Medium]]></description>
        <link>https://medium.com/@reese.amarshall?source=rss-f334f99a8b75------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rmUb0cQKDqXv_bRC</url>
            <title>Stories by Reese Marshall on Medium</title>
            <link>https://medium.com/@reese.amarshall?source=rss-f334f99a8b75------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:02:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reese.amarshall/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Apex Charts: Data Visualization Made Easy]]></title>
            <link>https://medium.com/@reese.amarshall/apex-charts-data-visualization-made-easy-aa1f66ef364?source=rss-f334f99a8b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa1f66ef364</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Reese Marshall]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 20:30:39 GMT</pubDate>
            <atom:updated>2023-03-29T20:30:39.778Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you working on a project and need to add some flare to your data? Look no further than Apex Charts for a simple way to integrate graphs or charts into your projects! This blog will be covering how to install it, implementing it into your project, and how to populate your data inside of your charts and or graphs. This blog is targeted toward those with an intermediate level of coding, and I will be using react.js in my examples, though Apex Charts can also be used in JavaScript, Vue, and Angular.</p><p>To get started, cd into the repository that your project is in and enter the following command:</p><pre>npm install apexcharts --save</pre><p>With this done, you can create a new js file for your charting data. Below is the code to create a line chart. If you would like to follow along, feel free to copy this code and try it out for yourself!</p><pre>import React, { Component } from &quot;react&quot;;<br>import Chart from &quot;react-apexcharts&quot;;<br><br>class Chart extends React.Component {<br>        constructor(props) {<br>          super(props);<br><br>          this.state = {<br>          <br>            series: [{<br>                name: &quot;Desktops&quot;,<br>                data: [10, 41, 35, 51, 49, 62, 69, 91, 148]<br>            }],<br>            options: {<br>              chart: {<br>                height: 350,<br>                type: &#39;line&#39;,<br>                zoom: {<br>                  enabled: false<br>                }<br>              },<br>              dataLabels: {<br>                enabled: false<br>              },<br>              stroke: {<br>                curve: &#39;straight&#39;<br>              },<br>              title: {<br>                text: &#39;Product Trends by Month&#39;,<br>                align: &#39;left&#39;<br>              },<br>              grid: {<br>                row: {<br>                  colors: [&#39;#f3f3f3&#39;, &#39;transparent&#39;], // takes an array which will be repeated on columns<br>                  opacity: 0.5<br>                },<br>              },<br>              xaxis: {<br>                categories: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;, &#39;Jun&#39;, &#39;Jul&#39;, &#39;Aug&#39;, &#39;Sep&#39;],<br>              }<br>            },<br>          <br>          <br>          };<br>        }<br><br>      <br><br>        render() {<br>          return (<br><br>      &lt;div id=&quot;chart&quot;&gt;<br>  &lt;ReactApexChart options={this.state.options} series={this.state.series} type=&quot;line&quot; height={350} /&gt;<br>&lt;/div&gt;<br><br>          );<br>        }<br>      }<br>export default Chart;</pre><p>I bet this looks very complex on first glance, and you may be a little intimidating at first, but it’s a lot simpler than it looks, and the bulk of what you would need to do is already handled for you. In this code, we’re creating a div element with an ID of “chart”, which will contain our chart. We then create a new instance of Apex Charts and pass in the ID of the chart container, as well as the data for the chart.</p><p>Our chart has one series named “Desktops”, and its data is an array of numbers representing the desktops sold for each month. We’re also specifying the categories for the x-axis using the “categories” property. Finally, we call the “render” method to render the chart. Make sure that you import your Chart.js file into your main component that’s rendering all of your pages.</p><pre>import Chart from &#39;./Chart&#39;<br><br>function App() {<br><br>  return (<br>        &lt;Chart/&gt;<br>    )<br>}<br>export default App;</pre><p>This will now render your chart, but what if you didn’t want to hard code stats into your graph, and instead you wanted a graph that updated datapoints that you’ve already mapped out? To do that we would need to pass down props.</p><pre>class Chart extends React.Component {</pre><p>Looks like we have a bit of a problem. There’s nowhere to pass down props! I know what you’re thinking, just add some parenthesis after Chart and pass the props and destructor them there. Unfortunately that will not work, so we need to use a different method for this. First lets make sure we’re passing down our props.</p><pre>import Chart from &#39;./Chart&#39;<br>import {useState, useEffect} from react;<br><br>function App() {<br>  <br>const [user, setUser] = useState([])<br><br>useEffect(() =&gt; {<br>  fetch(&#39;/user&#39;)<br>  .then(response =&gt; response.json())<br>  .then(userData =&gt; {<br>      setUser(userData)<br>  })<br>  }, [])<br><br><br>  return (<br>        &lt;Chart user={user}/&gt;<br>    )<br>}<br>export default App;</pre><p>Now that we have passed down our props, we can use them by placing our props where our data for our chart would go. You first would call props, the prop that you passed down, then whichever variable associated with the prop you passed down, in this case, we will call the number of desktops the user has. The syntax will look something like this.</p><pre>data: [props.user.number_of_desktops]</pre><p>Putting it all together it will look like this.</p><pre>import React, { Component } from &quot;react&quot;;<br>import Chart from &quot;react-apexcharts&quot;;<br><br>class Chart extends React.Component {<br>        constructor(props) {<br>          super(props);<br><br>          this.state = {<br>          <br>            series: [{<br>                name: &quot;Desktops&quot;,<br>                data: [props.user.number_of_desktops]<br>            }],<br>            options: {<br>              chart: {<br>                height: 350,<br>                type: &#39;line&#39;,<br>                zoom: {<br>                  enabled: false<br>                }<br>              },<br>              dataLabels: {<br>                enabled: false<br>              },<br>              stroke: {<br>                curve: &#39;straight&#39;<br>              },<br>              title: {<br>                text: &#39;Product Trends by Month&#39;,<br>                align: &#39;left&#39;<br>              },<br>              grid: {<br>                row: {<br>                  colors: [&#39;#f3f3f3&#39;, &#39;transparent&#39;], // takes an array which will be repeated on columns<br>                  opacity: 0.5<br>                },<br>              },<br>              xaxis: {<br>                categories: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;, &#39;Jun&#39;, &#39;Jul&#39;, &#39;Aug&#39;, &#39;Sep&#39;],<br>              }<br>            },<br>          <br>          <br>          };<br>        }<br><br>      <br><br>        render() {<br>          return (<br><br>      &lt;div id=&quot;chart&quot;&gt;<br>  &lt;ReactApexChart options={this.state.options} series={this.state.series} type=&quot;line&quot; height={350} /&gt;<br>&lt;/div&gt;<br><br>          );<br>        }<br>      }<br>export default Chart;</pre><p>You are now using your own data inside of the charts! if you would like to populate the chart with more data, all you need to do is add another comma and call on another user instance in this case following the same syntax.</p><p>I hope this very brief blog was able to help you add and edit your very own charts or graphs into your projects, as well as giving a cogent explanation on how Apex Charts works. Below I’ve included some resources for you to further your learning on other chart types and or graphs, as well as help with understanding them. Happy coding!</p><ul><li><a href="https://apexcharts.com/react-chart-demos/line-charts/basic/">React Line Chart - Basic Demo - ApexCharts.js</a></li><li><a href="https://apexcharts.com/docs/options/xaxis/#">xaxis - ApexCharts.js</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa1f66ef364" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validations,Authentication, and Authorizeation: Keeping Our Data Clean and Safe]]></title>
            <link>https://medium.com/@reese.amarshall/validations-authentication-and-authorizeation-keeping-our-data-clean-and-safe-7691f5204bb7?source=rss-f334f99a8b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/7691f5204bb7</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Reese Marshall]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 22:40:27 GMT</pubDate>
            <atom:updated>2023-03-07T22:40:27.564Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever tried logging onto social media, or into your bank account, only for it to say that you’ve entered the wrong password? You have validations to thank for that. It may seem annoying at first, but validations are an essential in data protection. Without validations, anyone would be able to log into anyone’s account and steal their data! Validations can be used to validate both client-side and server-side data, but in this blog, we’ll focus on server-side validations using Ruby on Rails. This will be targeted to those with an intermediate level of coding and understanding of ruby on rails.</p><p>Validations are a set of rules that ensure that the data entered into the database is correct and meets the specified criteria. When creating an application, it’s crucial to ensure that the data being entered is valid to prevent issues such as data inconsistency and errors in processing the data. Let’s look at an example of this. For this example, we will be using a model called User.</p><h3>Tip:</h3><p>If you want to practice this, you will need to generate a migration for “User” so that your rails application will auto generate a “User” model. You can do this by typing: “rails g resource User name password_digest.” This will create a migration inside your database with name and password being a component of the “User” migration, a schema file, a model, and a controller for “User.”</p><pre>class User &lt; ApplicationRecord<br>  validates :name, presence: true, uniqueness: true<br>  validates :password, presence: true<br><br>  has_secure_password<br>end</pre><p>With your model created, you now need to simply add your validations. You will type validates for each component of your migration table then the name of the component that you would like to add a validation to. In this case, we’re adding a validation to name, then setting the presence to true. and setting the uniqueness to true. Setting the presence to true makes it so that when users are creating a name, it cannot be left blank as well as for passwords. Setting the uniqueness to true makes it so that if a user attempts to create an account with the same name as another user in the database, it will reject their attempt at creating a username.</p><p>The last change we will add to our model is “has_secure_password.” What this does is adds an extra layer of protection to passwords that get added to your database. If you noticed earlier, we entered “password_digest” as a component instead of just password. Ruby on Rails has a pre-built method used to securely store and authenticate passwords for users. This adds encryption to whatever passwords are added to the database. When a user creates an account or updates their password, their password is passed through “password_ digest, which encrypts the password using the bcrypt algorithm and stores the resulting hash in the database. When the user attempts to log in, their password is again passed through password_digest, and the resulting hash is compared to the stored hash in the database. If the two hashes match, the user is authenticated and allowed to log in. Make sure that you have the gemfile “bcrypt” in your gemfile.rb if you would like to access this encryption method in your projects.</p><p>There are a plethora of other validations and metrics which you can add to these validations to increase security and streamline data that gets entered into your database. I’ve included a list of different types of validations you can add if you’re interested in learning more.</p><p>The last thing we need to do is create a sessions controller and add sessions into our routes . Lets first create the sessions controller by typing: “rails g controller Session create destroy.” This will create the controller and will also add your methods for create and destroy, which corresponds with login for create, and logout for destroy. Here’s how it will look like:</p><pre>class SessionsController &lt; ApplicationController<br>  def create<br>    user = User.find_by(username: params[:username])<br>    session[:user_id] = user.id<br>   render json: user<br>  end<br><br>  def destroy<br> session.delete :user_id<br> head :no_content<br>  end<br>end</pre><p>What this does it makes it so if a user is able to log in, they will be able to stay logged in, even on page refresh, and if they log out, they stay logged out until they log back in. For improved security, you may also want to include a time limit for your session that will automatically sign out a user, or conversely have a user set their account to stay logged in if they’re on a device that’s not shared amongst others. Now we just need to add the sessions to our routes. In your routes.rb file, you will notice that there should be one already included for your user when you first did your migration. All we need to do is add:</p><pre>  post &quot;/login&quot;, to: &quot;sessions#create&quot;<br>  delete &quot;/logout&quot;, to: &quot;sessions#destroy&quot;</pre><p>This will complete the bridge between a user being able to log in, access their data, and being able to log out, protecting their data. You have now completed your authorizations and authentications for your app!</p><p>I hope this brief blog offered a cogent explanation of what validations are, why it’s important, and how to apply them in project’s you’re building. Below are some resources that I used that helped me write this blog, and that can also help you further your understanding. Happy coding!</p><ul><li><a href="https://guides.rubyonrails.org/active_record_validations.html">Active Record Validations - Ruby on Rails Guides</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation">Client-side form validation - Learn web development | MDN</a></li><li><a href="https://guides.rubyonrails.org/security.html">Securing Rails Applications - Ruby on Rails Guides</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7691f5204bb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create migrations and manipulate data with Ruby]]></title>
            <link>https://medium.com/@reese.amarshall/how-to-create-migrations-and-manipulate-data-with-ruby-aaa0188faa88?source=rss-f334f99a8b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaa0188faa88</guid>
            <category><![CDATA[methods]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Reese Marshall]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 20:56:24 GMT</pubDate>
            <atom:updated>2023-02-15T20:56:24.792Z</atom:updated>
            <content:encoded><![CDATA[<p>So you’re new to Ruby, and you’re ready to start a project, Well you’ve come to the right place. To do this, we will be creating; migrations, tables, and seeds all to build a database that we can then manipulate. This blog is targeted at those new to Ruby, but that have a fundamental understanding of coding. You will need a code editor such as Visual Studio Code, and SQLite3 to make your table data visible</p><h3>Migrations</h3><p>There are a few things we need to do to have our data become visible, the first of which is migrations. Migrations are Ruby scripts that modify the database schema, a file that once you create your first migration, will be automatically generated. They are designed to be version-controlled, which means that you can make changes to the database schema over time, and each change is tracked in a separate migration file. Migrations are used to add or remove tables, columns, and indexes from the database schema. They also help to maintain data integrity by enforcing constraints on the database. Lets look at an example. Lets say you wanted to wanted to create a table for users. In your terminal, you will type:</p><pre>rake db:create_migration NAME=create_users</pre><p>This will create a new file for your migration, will generate a schema file, and both of these will be nested inside of a database file. Your new file for the migration you just created will have the name of your migration and you can now create your table and declare your data types.</p><pre>class CreateUsers &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :users do |t|<br>      t.string :name<br>      t.string :email<br>      t.string :password<br>      t.timestamps<br>    end<br>  end<br>end</pre><p>The most common data types are strings, integers, booleans, and date. You may also notice that it already includes t.timestamp. This will simply date whenever a change has been made to the database. The only other thing left to do is assign the name of the variable for each datatype, and migrate your changes by typing:</p><pre>rake db:migrate</pre><h3>Tip:</h3><p>At any point you make a mistake the naming of a table or variable, you can always use the command “rake db:rollback” to undo the last migration you’ve made. You can also use the command “rake db:migrate:status” to check the status of your migrations. If the migration status is up, you are good to go!</p><p>Depending on what kind of project you’re building, you may have more than one table, in which case you will just create a migration for each table that you need. At this point you can open your table with SQLite3 by right clicking the development.sqlite3 file in your database file and clicking open database, but we have a problem; We don’t have any data in our database to see! In order to add data to our tables, we will need to create a file called seeds.rb in our database, and in this file we will be able to add data into our tables.</p><h3>Seed</h3><p>Creating seeds is a simple task, all you need to do is call the name of the variable you named your table after, an assign each variable of the table a value. Let’s look at an example.</p><pre>User.create(name: &quot;John&quot;, email: &quot;johndoe@example.com&quot;, password: &quot;abc123&quot;)</pre><p>You can create as many seeds as you’d like this way for any variables you declare. To populate your table with this new data you created you should enter into your terminal:</p><pre>rake db:seed</pre><p>Now take a look at your table; you should see the new data you just created!</p><h3>Manipulating and Sorting Data</h3><p>In our example code so far, we only have one table populated with data, but what if we had hundreds or even thousands of entries in our database or if we had multiple tables that we wanted to cross reference? Well this is where models come into play. Models are often used to represent data that is stored in a database or other data store. They define the attributes of the object, as well as any methods that are associated with it. To create a model you will create a new ruby file named after the name of your variable you would like to manipulate. It would look something like this:</p><pre>class User &lt; ActiveRecord::Base<br><br>end</pre><p>Inside of your class, you will write your associations for any other tables that you would like the table you’re currently working with to interact with. These associations will allow you to express the relationships between objects in your application. There are a few different associations, and you will need to choose the appropriate one for your models. Here are a few different associations:</p><ol><li>“Belongs to” association: This is a one-to-one relationship where one model belongs to another model. For example, a comment belongs to a post.</li><li>“Has one” association: This is the inverse of the “belongs to” association, where one model has one associated model. For example, a post has one author.</li><li>“Has many” association: This is a one-to-many relationship where one model has many associated models. For example, a post has many comments.</li><li>“Has many through” association: This is a way to define a many-to-many relationship using a join model. For example, a doctor has many patients through appointments.</li><li>“Has and belongs to many” association: This is another way to define a many-to-many relationship, without the need for a join model. For example, a post can have many tags, and a tag can be applied to many posts.</li></ol><p>Lets say we created two more tables, one for posts, and another for comments. To link these these tables I would use a “has_many” and “has many though” association for Users and Posts and a “belongs_to” association for comments. This will go inside each of the models within the class. Here’s an example of how it would look:</p><pre>class User &lt; ActiveRecord::Base<br>has_many :comments<br>has_many :posts, through: :comments<br>end</pre><pre>class Post &lt; ActiveRecord::Base<br>has_many :comments<br>has_many :users, through: :comments<br>end</pre><pre>class Comment &lt; ActiveRecord::Base<br>belongs_to :post<br>belongs_to :user<br>end</pre><p>With your associations completed, you can now write methods for your that will manipulate your data inside of your models, and or you can get or update data inside of your console. Lets look at an example buy updating our User database. First you would open your console with “rake console” inside of your console, you can type:</p><pre>User.all.find(1).update(name: &quot;Josh&quot;)</pre><p>“User” is the name of the database we are checking, “.all” grabs all of the data within that database, .find() will grab the id input and return the data from that id, “.update” is what will change that value, and lastly you will call the variable that you wish to change in parenthesis.</p><h3>Tip:</h3><p>If you would like to test these changes in your console again, you will need to exit the console by typing “exit” then you will open your console again and search for your new entry. Ruby won’t recognize any changes without first exiting the console!</p><p>Check out your database. You’ll notice that you’ve now updated a value within your table! There are a plethora of different methods, and different ways of manipulating data within ruby. However, there are too many to go into depth about each, so I’ve included a resource that you can use to check out these methods.</p><p>I hope this blog has been helpful in understanding on how to get started in ruby. Below I have included a few resources that were helpful to me when I first started using ruby as well as writing this blog.</p><ul><li><a href="https://guides.rubyonrails.org/association_basics.html">Active Record Associations - Ruby on Rails Guides</a></li><li><a href="https://guides.rubyonrails.org/active_record_migrations.html">Active Record Migrations - Ruby on Rails Guides</a></li><li><a href="https://www.freecodecamp.org/news/common-array-methods-in-ruby/">Most Common Ruby Array Methods You Should Know</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaa0188faa88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filters: Sorting Made Easy]]></title>
            <link>https://medium.com/@reese.amarshall/filters-sorting-made-easy-3c5a544beca7?source=rss-f334f99a8b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c5a544beca7</guid>
            <dc:creator><![CDATA[Reese Marshall]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 22:05:30 GMT</pubDate>
            <atom:updated>2023-01-23T22:05:30.774Z</atom:updated>
            <content:encoded><![CDATA[<p>Filters are something that make our lives easier when it comes to sorting through data. Filters have become so prevalent you probably don’t realize you’re using them. Whether it’s for finding something to watch on Netflix, googling something, scrolling through social media, or shopping online, filters are there to save us time and get the information we’re looking for to us as quick as possible. If you’re reading this, You probably want to know how to create and implement a filter into whatever you’re building. Below I will explain what filters are, how they work, how to create one, how to make it work, and how to improve functionality for the filters. This blog’s target audience will be for those who have a fundamental understanding of “<em>React</em>”, and an intermidiate level of coding.</p><h3>Filter()</h3><p>In JavaScript, the filter() method is used to create a new array with all elements that pass the test implemented by the provided function. The function is called for each element of the array, and the element is included in the new array if the function returns a truthy value. Lets say you were building an App for plants and you have already appended your data, pictures and design for the plants. There are lots of different plants for users to look at, so you want to add a filter to help filter through these. Here’s an example of how to build this out:</p><pre>import React from &quot;react&quot;;<br><br><br>function Search() {<br>  return (<br>    &lt;div className=&quot;searchbar&quot;&gt;<br>      &lt;label htmlFor=&quot;search&quot;&gt;Search Plants:&lt;/label&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        id=&quot;search&quot;<br>        placeholder=&quot;Type a name to search...&quot;<br>        }}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br><br>export default Search;</pre><p>You would start by creating a new js file for your search filter and writing the html for the search-bar inside of your return. This will create a search-bar for your App, but there are a few more steps necessary to actually make it functional.</p><h3>useState</h3><p>To add functionality to our search filter, we need to to make use of useState. In your main App js file, you will import . The reason we need to use useState is because it takes an initial value as an argument, and returns an array containing the current state value and a function to update it. Without it, we wouldn’t see any live changes from the client side of the App. Here’s how it would look in regards to our plant website:</p><pre>import React, { useState } from &quot;react&quot;;<br><br><br>const [filteredPlants, setFilteredPlants] = useState([])<br>const [searchText, setSearchText] = useState(&quot;&quot;)<br><br> return (<br>    &lt;&gt;<br>    &lt;Search /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br><br>export default PlantPage;</pre><p>We created a const and a use state for our filter and for the text that will be inserted into the filter by the user. The reason for this is so that we can return a new array based on the information inserted into the filter for our filter variable, and for the search-text, it allows for the filter to start with no input from the user, and therefore no filter applied to the search results. As the user enters text into the search field, the state updates to reflect the current input, and the filter is applied to the search results based on the updated state. With our useStates declared, we can now apply these to a couple of functions we need to create to use these new variables, and apply them to the filter as well as applying these to a useEffect.</p><h3>useEffect</h3><p>Next we will make use of useEffect for our variables. The reason for this is because it allows us to synchronize a component with an external system, listen for changes to the filter state, and update the search results accordingly. it will also clean up any effects that were used in a previous render i.e. previous text inputs. At this point, useEffect should’ve already been imported if you have done a GET request to append your images on your page. You will add the variable you created for your filter to your first GET request so that you will see your plants that are searched for through the filter.</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>const [filteredPlants, setFilteredPlants] = useState([])<br>const [searchText, setSearchText] = useState(&quot;&quot;)<br><br>useEffect(() =&gt; {<br>  fetch(&quot;http://localhost:3000/plants&quot;)<br>    .then(response =&gt; response.json())<br>    .then(plantData =&gt; {<br>      setPlants(plantData);<br>      setFilteredPlants(plantData)<br>    });<br>}, []);<br><br><br><br> return (<br>    &lt;&gt;<br>    &lt;Search /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default PlantPage;</pre><p>Now we will create a function that will handle the on change event for our filter, and add increased functionality to our filter to allow it to handle for case sensitivity.</p><pre>function filterThePlants(inputText){<br>  if(inputText === &quot;&quot;) {<br>    setFilteredPlants(plants)<br>  }</pre><p>Above, I’ve written out the function that will handle the onChange event in your Search js. file. Lets go through this step by step. Inside of our function we are including input text as a parameter because we want to create a conditional for the text that will be displayed based on the user’s input. For our conditional, we want to make use of the states we created earlier for if there’s nothing input into the search bar. If this is the case, we will display everything on the page. In the event that we type something into our filter, we want to only display results matching the values of whatever we typed in the search bar. It will look something like this:</p><pre>else {<br>    setFilteredPlants(plants.filter(plant =&gt; {<br>      return plant.name.toLowerCase().includes(inputText.toLowerCase())<br>    }))<br>  }</pre><p>Here were utilizing the filter display the name of whatever plant is input, and included .toLowerCase() to allow for case sensitivity followed by .includes(inputText.toLowerCase()) to allow either upper or lower case inputs to render results, improving the functionality of our search bar. The last thing we need to do for this step is to create another useEffect for our filter.</p><pre>useEffect(() =&gt; filterThePlants(searchText), [plants])</pre><p>This use effect will call on our event handler for the text input into our filter, and utilize a dependancy of our main variable. Without it, we wouldn’t see the name of the plant we type in render. Our final step in our filter creation is to pass down our props into our Search js file, and call on our conditional for our filter function and setter for our setSearchText inside our on change event.</p><h3>OnChange</h3><p>This last step is a simple one. We are adding an on change event to our return, then passing the props into our event. We are specifically targeting the value of whatever is typed into the search filter, so we will write our onChange event like this:</p><pre>onChange={(e) =&gt; {<br>          filterThePlants(e.target.value)<br>          setSearchText(e.target.value)<br>        }}</pre><p>Don’t forget to include the props of the inside of your search function:</p><pre>function Search({filterThePlants, setSearchText}) {</pre><p>With that, your search filter is now complete, and you have added extra functionality to it!</p><h3>Tip:</h3><p>If you do decide to create a search filter, you will need to redeclare the name of your main variable to include your filter, on your main app page, as well as on wherever you pass this variable down as props i.e. the page where you mapped your data out. If not, your filtered data will not render!</p><p>Filters were created to make the lives of everyone who uses them easier and allow users to quickly sort through data. Hopefully, my examples have made understanding filters palatable, and easy to understand. Below, I’ve included some links to some resources that has helped me understand filters, and will hopefully be of use to you.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">Array.prototype.filter() - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering">React interactivity: Editing, filtering, conditional rendering - Learn web development | MDN</a></li><li><a href="https://www.fullstacklabs.co/blog/building-a-responsive-filter-component-on-react">Building a Responsive Filter Component on React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c5a544beca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetch & Its Many Uses]]></title>
            <link>https://medium.com/@reese.amarshall/fetch-its-many-uses-43e4320702d4?source=rss-f334f99a8b75------2</link>
            <guid isPermaLink="false">https://medium.com/p/43e4320702d4</guid>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[fetch]]></category>
            <dc:creator><![CDATA[Reese Marshall]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 08:02:55 GMT</pubDate>
            <atom:updated>2023-01-04T08:02:55.853Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you started coding and need to use fetch functions, only to find yourself going down a rabbit hole trying to understand it all, and end up even more confused than when you started? I know I have, which is is why I will be explaining how fetch works, what its main applications are, and when you will use each of these applications. This blog will be mainly focused on those who are relatively new to coding, but it can be used by anyone who needs and or wants a refresher in using fetch. I will also primarily be focusing on GET, POST, PATCH, and DELETE, requests for fetch.</p><h3><strong>Fetch()</strong></h3><p>Lets start by describing what fetch is. Fetch is a method of requesting data from a server and or external API or “Application Programming Interface”. This then returns said data JSON or XML. For the purposes of this blog, we will focus on JSON, which stands for “JavaScript Object Notation.” So what does all of this mean? Simply put, fetch is used to “fetch” data that is elsewhere, and it is being converted into JSON or XML, or in other words, something that is readable in your JavaScript that you are writing. Lets look at an example to further break this down.</p><pre>fetch(&#39;http://example.com/data/123&#39;)</pre><p>This is how the code for the fetch will initially look, regardless of what kind of request you are making. You will declare your fetch, then inside of parenthesis, then copy and paste the link to your API inside of quotations. That’s it! you’ve got the beginning of your fetch. But we still have a problem. As mentioned before, fetch grabs the information from an API, but it can’t read the data yet! It would be like if you were in a foreign country looking up directions in a language you’re not familiar with. Sure you have the directions, but you can’t read them! This where the type of request your making comes in handy. The code you write for the type of request you’re making will change how this gets translated. This leads to the first method we will cover GET requests.</p><pre>fetch(&#39;http://example.com/data.json?q=search_query&#39;)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; {<br>    // do something with the data<br>  });</pre><h3>GET Requests:</h3><p>Above is an example of how the code for a get request will look. The first line of code is for the fetch itself, and the link to the API it is fetching data from. The next part is unique to a GET request because GET requests don’t modify data that is being fetched. Your next line of code is what translates the API data into something readable or in this case, JSON. The .then is the beginning of a sequence of events that will occur for it to translate this data. You are getting a response from the server, writing your arrow function then translating it to JSON with response.json(). This makes your API data readable! Now that your data is readable, you are going to write your second .then line of code so that you can write whatever code you need. To do this write a second .then, and include a parameter. Typically this will be named after the main subject of your API, then you follow this with an arrow function and a curly brace. You have now written a GET request! The only thing left is to write whatever code you need that will be interacting with the data you are “getting.”</p><h3>Tip:</h3><p>Get requests do not persist! This means that any changes made on a webpage with a GET request will not stay there when the page is refreshed as it does not update any backend data.</p><pre>Copy code<br>fetch(&#39;/some/endpoint&#39;, {<br>  method: &#39;PATCH&#39;,<br>  body: JSON.stringify({<br>    key: &#39;value&#39;<br>  }),<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>  }<br>});</pre><h3>PATCH Requests:</h3><p>Next is our PATCH request. You will notice in the example above that things are a lot more complex, but that’s ok! PATCH requests are used to partially modify certain aspects of a resource instead of replacing the whole thing. Another way of looking at a patch request would be like a car getting a flat tire. You don’t want to replace the entire car for something so trivial, so you’re only addressing the problem at hand. The format of PATCH requests and similarly the subsequent requests from this point on will look similar to this, so once you understand the formatting, these will become easy to understand. Just like every other request, you will start with fetch, except this time, your fetch will contain two arguments: The “endpoint” or the URL you want to send your request to, and the options object. This object is subject to change depending on what you would like to include in your request. Let’s go through this next step slowly. The second argument or in other words the “object” of your fetch for a PATCH request, starts with the method. The method is just you choosing what kind of request you’re making, which in this case is a PATCH request. In the next line of code we have our body, which will contain the data that we want to send. We still haven’t translated our data into something readable, which is where the next line of code comes in. JSON.stringify({ }) will turn the subsequent key and value placed inside of this as something readable in your javascript. What’s really occurring is .stringify is parsing the values inside of the parenthesis and curly braces into a string. The last line of code is for your headers, which provides additional information being sent in the request. There are a few uses for this, but for simplicity’s sake, we will just focus on Content-type. This indicates the media type of the body, or in other words the format. To do this you would write ‘Content-Type’: ‘application/json.’ We are now done with our PATCH request! Next we will go over POST requests.</p><pre>fetch(&#39;/resource&#39;, {<br>  method: &#39;POST&#39;,<br>  body: JSON.stringify({<br>    field1: &#39;value1&#39;,<br>    field2: &#39;value2&#39;<br>  }),<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>  }<br>});</pre><h3>POST Requests:</h3><p>Here is an example of what a POST request would look like. Lets start with the functionality of a POST request. POST requests are typically used when you’re uploading a file or submitting a form to a specified location. To put it another way, it would be as if you were giving mail to the mailman, then they would take it to the post office for it to later be utilized or sorted. To start, we write our fetch line of code with the resource we will be referencing. Next is the method, which in this case, we’re making a POST request. The body will also be the same as when we were doing our PATCH request where you need to translate the data into a readable string with JSON.stringify. This is where the code begins to look different. The next line of code contains your fields, and the subsequent values within those fields. So if you had a submit form, the field would be the submit form you’re targeting, and the value would be the value inside of the selected form that would then be “posted” once you click your submit button for that form. The last thing is the headers, which is the same thing as what you would do for a PATCH request. Now you have completed a POST request! Onto our last type of request we will be covering, DELETE requests.</p><pre>fetch(&#39;https://example.com/delete-resource&#39;, {<br>  method: &#39;DELETE&#39;<br>});</pre><h3>DELETE Requests:</h3><p>Our last fetch request we will be covering are DELETE requests, which do exactly what it sounds like it does. It is sending a delete request to the specified resource in the URL inside of your fetch line of code. While the example above is very simplistic, DELETE requests don’t need to include a body or headers within the fetch code itself, but you can if you want to get more specific. To start writing a DELETE request, you will write your fetch line of code, the URL of the API you are accessing, then following up with /delete hyphenated wit the name of your resource you would like to delete. The last mandatory step would be to declare your method, which again is a DELETE request. That’s it! Your specified resource should now be deleted.</p><h3>Tip:</h3><p>PATCH, POST, AND DELETE requests are fetch methods that persist! This means that changes you make will continue to exist, even after you finish your fetch request.</p><p>All in all, fetch is a very useful tool that allows you to communicate with API’s to make a variety of different requests. These might seem like a lot to digest at first, but I hope that I’ve been able to lay out fetch in a palatable way that makes sense. Below I’ve included some sources that you can utilize to go further in-depth with fetch. I hope my explanations were of good use, and good luck in your future coding journey!</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/fetch">fetch() - Web APIs | MDN</a></li><li><a href="https://www.geeksforgeeks.org/javascript-fetch-method/">JavaScript fetch() Method - GeeksforGeeks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43e4320702d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>