<?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 Manuel Casanova on Medium]]></title>
        <description><![CDATA[Stories by Manuel Casanova on Medium]]></description>
        <link>https://medium.com/@manuelcasanovafernandez?source=rss-612db93dd210------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ii1_yh7JufkJiqj1</url>
            <title>Stories by Manuel Casanova on Medium</title>
            <link>https://medium.com/@manuelcasanovafernandez?source=rss-612db93dd210------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:24:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manuelcasanovafernandez/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[A PERN STACK CRUD APPLICATION TUTORIAL]]></title>
            <link>https://medium.com/@manuelcasanovafernandez/a-pern-stack-crud-application-tutorial-e8676582c708?source=rss-612db93dd210------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8676582c708</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Manuel Casanova]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 21:38:56 GMT</pubDate>
            <atom:updated>2022-07-25T20:11:00.126Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL, Express, React, NodeJs / Favourite movies list</p><blockquote>This article is a tutorial to create a simple CRUD application with the PERN stack. It has been written by a bootcamp student with limited experience and, therefore, some bad practices, no-DRY code, and inaccurate explanation of the use of dependencies and libraries should be expected.</blockquote><blockquote>Thanks to <a href="https://idbentley.com/">Ian Bentley</a>, who mentored me the many times I was stuck learning how to do this project.</blockquote><p>The acronym CRUD stands for “Create, Read, Update and Delete”. With this application, a user will be able to see (<strong>read</strong>) a list of movies and genres, add (<strong>create</strong>) movies and genres to the list, edit (<strong>update</strong>) and <strong>delete</strong> both movies and genres from the list.</p><p>The PERN stack stands for PostgreSQL, Express, React and Node.js. Each of them will be briefly explained.</p><blockquote>This tutorial assumes that you have Node.js, PostgreSQL and a code editor like Virtual Studio Code installed. The tutorial will use the MAC terminal.</blockquote><p><strong>INDEX</strong></p><ol><li><a href="#2156">Application use demonstration</a></li><li><a href="#3861">Overview diagram</a></li><li><a href="#b328">Github</a></li><li><a href="#a289">Database</a></li><li><a href="#0024">Server Setup and Dependencies Installation</a></li><li><a href="#5952">Server and database connection</a></li><li><a href="#9A29">Client set up</a></li><li><a href="#659F">Creation of components</a></li><li><a href="#8c48">Branches</a></li><li><a href="#75e9">Add functionality to components — READ</a></li><li><a href="#33ef">Add functionality to components — DELETE</a></li><li><a href="#7c3e">Add functionality to components — CREATE</a></li><li><a href="#42e8">Add functionality to components — UPDATE</a></li><li><a href="#62c6">Extras</a></li></ol><h4><strong>1. APPLICATION USE DEMONSTRATION</strong></h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F28bl5BkKrTs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D28bl5BkKrTs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F28bl5BkKrTs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7379d58b22d90889c12293b60c99b626/href">https://medium.com/media/7379d58b22d90889c12293b60c99b626/href</a></iframe><h4><strong>2. OVERVIERW DIAGRAM</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCuSQwIwSP22TLF3Z3BAKA.png" /></figure><p>Once this application is completed, the user -by clicking on the ADD, EDIT or DELETE buttons- will be sending HTTP requests from the front-end (REACT) to our restful API (the server, the backend).</p><blockquote>An API, or application programming interface, is a set of rules that define how applications or devices can connect to and communicate with each other. A REST API is an API that conforms to the design principles of the REST, or representational state transfer architectural style. For this reason, REST APIs are sometimes referred to RESTful APIs.</blockquote><blockquote>IBM Cloud Education — <a href="https://www.ibm.com/cloud/learn/rest-apis">https://www.ibm.com/cloud/learn/rest-apis</a></blockquote><p>Depending on the http request and the route that has been hit, it is going to instruct the database (postgreSQL) on what type of CRUD operation needs to get done. CRUD operations do not happen in the restful API, but on the database.</p><p>For example, when the user clicks on the Add movie button, the user is sending from the front-end a post request to create a movie to the back end, which then instructs the database to do so.</p><blockquote><em>“CRUD operations do not happen in the restful API, but on the database”</em></blockquote><h4><strong>3. GITHUB</strong></h4><p>We are going to create a github repository and connect it to the local storage. We will be committing changes often to github in order to easily see the different steps that we have taken. Also, for major features, we will be working on different branches. This will give you some experience with the use of github.</p><p><strong><em>From the terminal, create and access a directory named movies.</em></strong></p><pre>mkdir movies<br>cd movies</pre><p><strong><em>Initialize an empty repository.</em></strong></p><pre>git init</pre><p><strong><em>From your github page, create a New Repository.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*4GM5PkfJLat7hMId" /></figure><p><strong><em>Copy the SSH.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*m7U5YjKvNYUzCVvu" /></figure><p><strong><em>Back in your terminal connect your github repository with the local storage.</em></strong></p><pre>git remode add origin insert-here-ssh-code</pre><h4><strong>4. DATABASE</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*OUK4NNMycqvil67Ui1lDxw.png" /></figure><p><strong><em>In the movies directory, create a database directory and the files database.sql, tables.sql and seeds.sql.</em></strong></p><pre>mkdir database<br>cd database<br>touch database.sql<br>touch tables.sql<br>touch seeds.sql</pre><p>We can now do our first commit to github, to track the new files. If we enter in our terminal git status from the movies directory we will see the following message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*gXaS75OWN17EjhIA" /></figure><p>To commit the untracked files (the new folder and the files within it) we can use the following command:</p><pre>git add .<br>git commit -m &quot;Add new database folder and sql files&quot;</pre><p>The current branch (named master) has no upstream branch. In order to push it and set the remote as upstream, we will use the following code.</p><pre>git push --set-upstream origin master</pre><p>For subsequent pushes, we will use the command</p><pre>git push</pre><p>The next step is to create the database, the tables and add some default information for the tables (eventually, this default information -or seeds- will not be used, since we will be able to perform crud operations on these tables from the front-end).</p><p><strong><em>From your terminal, access PostgreSQL</em></strong></p><pre>PSQL</pre><p>Use the command \l or \listto see a list of the current databases.</p><p>Make sure you do not have a database named movies. If that is the case, choose a different name for the database for this app.</p><p><strong><em>In your code editor, open the file database.sql and add the instructions to create a database (change the name if it already exists).</em></strong></p><blockquote>The line DROP DATABASE IF EXISTS movies will delete any</blockquote><blockquote>existing database with that name.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*LDhMj3i5S7x55kSw" /></figure><p><strong><em>From your psql terminal, run this command to create the new database.</em></strong></p><pre>\i database/database.sql</pre><p><strong><em>You could also write directly on the psql terminal.</em></strong></p><pre>DROP DATABASE IF EXISTS movies;<br>CREATE DATABASE movies;</pre><p><strong><em>Move to the newly created database.</em></strong></p><pre>\c movies</pre><p>Create the tables. You could, again, write the code directly on the terminal. However, we will likely do some testing during the creation of the app and will want to, either make modifications to the tables or clean it up to start with a blank list. Therefore, it is recommended to use the files that we have created.</p><p><strong>In the tables.sql file, add this code:</strong></p><pre>DROP TABLE IF EXISTS movies CASCADE;</pre><pre>DROP TABLE IF EXISTS genres CASCADE;</pre><pre>CREATE TABLE genres (</pre><pre>genre_id SERIAL PRIMARY KEY NOT NULL,</pre><pre>genre_title VARCHAR(255) NOT NULL</pre><pre>);</pre><pre>CREATE TABLE movies (</pre><pre>movie_id SERIAL PRIMARY KEY NOT NULL,</pre><pre>movie_title VARCHAR(255) NOT NULL,</pre><pre>movie_year INTEGER,</pre><pre>movie_genre_id INTEGER REFERENCES genres(genre_id) ON DELETE CASCADE,</pre><pre>movie_imdb VARCHAR(255)</pre><pre>);</pre><blockquote>PostgreSQL needs very precise indications. Each comma, parentheses and semicolon are important. Missing any part of this code will result in an error.</blockquote><p><strong><em>Run it from the psql terminal with the code.</em></strong></p><pre>\i database/tables.sql</pre><p><strong><em>To see the new tables, enter into your psql terminal.</em></strong></p><pre>\dt</pre><p><strong><em>To see more details of the newly created tables, enter:</em></strong></p><pre><strong>SELECT * from movies;<br>SELECT * from genres;</strong></pre><p>Now, you can see the two empty tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*NxneK49TZ_IBp9QK" /></figure><p>Let’s add some information to them.</p><p><strong><em>In the seeds.sql file, enter this code with the instructions to add elements to the tables:</em></strong></p><pre>INSERT INTO genres (genre_title)</pre><pre>VALUES</pre><pre>(&#39;Drama&#39;),</pre><pre>(&#39;Comedy&#39;),</pre><pre>(&#39;Romance&#39;),</pre><pre>(&#39;Adventure&#39;);</pre><pre>INSERT INTO movies (movie_title, movie_year, movie_genre_id, movie_imdb) VALUES</pre><pre>(&#39;Forrest Gump&#39;, 1994, 1, &#39;https://www.imdb.com/title/tt0109830/&#39;),</pre><pre>(&#39;Dances with wolves&#39;, 1990, 4, &#39;https://www.imdb.com/title/tt0099348/&#39;);</pre><p>Then, run it from the psql terminal</p><pre>\i database/seeds.sql</pre><p>Now, if you use the SELECT statements again, you will see the information added to the tables of our database.</p><p>The SELECT statement is used in PostgreSQL to retrieve data from a table, also known as to query the table. These statements are also known as queries and, we will learn more in order to edit and delete information from the tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*U57TNZLmhCCdY4tt" /></figure><p>Time to commit and push changes to github. From your terminal, enter git status to see the files that have been modified. You could commit and push it all together with the following code:</p><pre>git add . <br>git commit -m “Message detailing the changes”<br>git push</pre><p>or one by one, for example:</p><pre>git add tables.sql<br>git commit -m “Add queries to create tables”<br>git push</pre><h4><strong>5. SERVER SETUP AND DEPENDENCIES INSTALLATION</strong></h4><p>Now, we are going to create our restful API.</p><p><strong><em>Open a new terminal (keep the terminal with PostgreSQL running for future reference), access the application folder, create a folder named server and access it.</em></strong></p><pre>cd movies<br>mkdir server<br>cd server</pre><p><strong><em>Inside the newly created server folder, enter </em></strong><em>npm init</em><strong><em>and press enter until you are asked `Is this OK? (yes)` Answer by entering </em></strong><em>y</em></p><p>You will notice that a new file, package.json is created. This is going to keep track of all packages and dependencies in our application. In other words, we will be installing some programs that will allow our application to connect and work, and we will be able to see them in this file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*SNF2XbEvibGuumKj" /></figure><p><strong><em>We will start installing some dependencies with the following code:</em></strong></p><p>npm i express pg cors axios</p><p>You can now see these dependencies in the package.json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*qNwU7r0oquMCy3IR" /></figure><blockquote><strong>Express</strong> allows us to quickly create a server.</blockquote><blockquote><strong>Cors</strong> allows different domain applications to interact with each other. Our server will be running on localhost:8001 and our front-end React application will be running on localhost:3000.</blockquote><blockquote><strong>PG</strong> helps connect our database and server in order to run postgreSQL queries.</blockquote><blockquote><strong>Axios</strong> is a promise-based HTTP client for JavaScript. It has the ability to make HTTP requests from the browser and handle the transformation of request and response data.</blockquote><p><strong><em>Do you want to commit and push the latest changes? Let’s do it</em></strong></p><pre>git add . <br>git commit -m “Create server folder, create a package json file, install dependencies express cors pg axios” <br>git push</pre><p><strong><em>Confirm that your branch is up to date by entering</em></strong> git status.</p><p>Let’s continue creating our back end.</p><p><strong><em>Inside your server folder, create an index.js file.</em></strong></p><pre>cd server<br>touch index.js</pre><p><strong><em>Add this code:</em></strong></p><pre>const express = require(&#39;express&#39;);</pre><pre>const app = express();</pre><pre>const port = 8001;</pre><pre>const cors = require(&#39;cors&#39;);</pre><pre>app.use(cors());</pre><pre>app.use(express.json()); //req.body</pre><pre>app.listen(port, () =&gt; {</pre><pre>console.log(`Movies app running on port ${port}.`);</pre><pre>});</pre><p>What is happening here? We are setting up our server!</p><p>Ok, cool… hey, Manuel! what is that express.json?</p><blockquote>According to the documentation, “express.json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser.</blockquote><blockquote>This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.”</blockquote><p>Ok, cool…hey, Manuel! Could you translate this into English?</p><p>When you are building a full stack application, you need to get data from the client side (for example, we will be entering inside some form the name of a movie). The way we do it is with the request.body object (we will be referencing this in the next steps). We use the express.json middleware to do so. Still confused? I know, me too. Remember that I am learning as well. Don’t worry, we’ll see this req.body several times.</p><p><strong><em>Run on your terminal </em></strong><em>node index.js</em><strong><em> and see the message:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*eY8-mQAFUXwWQUyd" /></figure><p><strong><em>Press</em></strong> ^C<strong><em>(control C) to stop the server.</em></strong></p><p>Now, during the development of this app, we will be making various changes and we don’t want to restart the server each time. In order to do so automatically, we are going to install a dependency called nodemon.</p><p><strong><em>Install nodemon.</em></strong></p><p>npm i nodemon</p><p><strong><em>Start our server by entering</em></strong> nodemon index.js.</p><p>Now, our server will look for changes in our app and restart automatically.</p><blockquote>Sometimes, the app does not work properly and we have to manually restart the server ^Cand nodemon index.jsHow to know when this happens? If your code seems to be well written but it does not work as expected, manually restart the server. There’s a chance that it will be the solution.</blockquote><p>We have a server running, cool! Well, not so fast. I mean, of course it’s cool. But the server is not serving anything so… is a server not serving anything actually a server? (Yeah, I know, a terrible joke).</p><p>Good moment to commit and push changes? Yes, why not? Do it. You now know how.</p><p>Now, let’s connect our server and postgreSQL database!</p><h4><strong>6. SERVER AND DATABASE CONNECTION</strong></h4><p>We are going to use the pg library that we previously installed.</p><p><strong><em>In our server folder, create a db.js file and insert the following code (use your user and password).</em></strong></p><pre>const Pool = require(&#39;pg&#39;).Pool;</pre><pre>const pool = new Pool({</pre><pre>user: &#39;**********&#39;,</pre><pre>host: &#39;localhost&#39;,</pre><pre>database: &#39;movies&#39;,</pre><pre>password: &#39;********&#39;,</pre><pre>port: 5432</pre><pre>})</pre><pre>module.exports = pool;</pre><p><strong><em>Import the pool in index.js (see line 5). By using the pool, we can now run queries with postgreSQL.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*Kd1s_4NRLg0gT1Rz" /></figure><h4><strong>7. CLIENT SETUP</strong></h4><p>At the moment, in our movies folder we have two subfolders: database -which includes the queries to create the database, the tables and seed these- and server, containing our restful api.</p><p>We are now going to add a third folder to hold our front-end / client. This time, though, we will use a different approach.</p><p><strong>In our terminal, inside our movies folder type</strong> npx create-react-app client</p><p>This process will take up to a minute depending on several factors and will create a series of subfolders in the client folder (we could name it differently if we wanted) that will hold the necessary files for our front-end .</p><p>As soon as the installation succeeds, we can run npm startfrom our movies/client directory and we’ll see how our browser opens a tag on localhost:3000 rendering a sample app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*l9cmpn6yQd2SxGSu" /></figure><p>That does not look much like the app we want to build, so let’s take some steps.</p><p>Before, is time to commit and push changes? Let’s do it. By now, you might have several terminal windows open: One to run the server, another one to run the app, a third one running PSQL and a fourth used to commit… It’s ok!</p><p>Have a look at the new client folder that was created with the react app. Play with the inspect tag on your browser.</p><p>You will see a public/index.html file with a &lt;div id=&quot;root&quot;&gt;&lt;/div&gt; This is basically where the app lives. As you can see, it renders a <strong>component</strong> named &lt;App /&gt;which is imported from the file src/App.js. That file contains what you can currently see at localhost:3000.</p><blockquote><strong>REACT Components</strong> are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML.</blockquote><blockquote><em>W3 Schools</em></blockquote><p>At this point, we are going to replace these contents with a very basic schema of our app. <strong><em>Open the client/src/App.js file and make it look like this:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/0*uhug158SQSq5rpoC" /></figure><p><strong><em>Confirm that your view at localhost:3000 has changed to:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/0*qA16PgaqMyslGQ0W" /></figure><p>This tutorial will not focus on the styling of the app, but on the functionality. I will provide you now with some basic styling. Copy and paste into the App.css file component the code from this file:</p><p><a href="https://gist.github.com/manuelcasanova/62a6247e7d1c67371e9750c8a9d30158">https://gist.github.com/manuelcasanova/62a6247e7d1c67371e9750c8a9d30158</a></p><p>We will also be using Bootstrap 4 to assist with styling.</p><blockquote>Bootstrap is a free and open-soruce CSS framework directed at responsive, mobile-first front-end web development. It contains HTML, CSS and (optionally) JavaScript-based design templates for typography, forms, buttons, navigation, and other interface components.</blockquote><blockquote><em>Wikipedia</em></blockquote><p><strong><em>Google Bootstrap 4 or use this link</em></strong> <a href="https://getbootstrap.com/docs/4.0/getting-started/introduction/">https://getbootstrap.com/docs/4.0/getting-started/introduction/</a></p><p><strong><em>In your public/index.html file, copy-paste the stylesheet</em></strong> &lt;link&gt; <strong><em>into your</em></strong> &lt;head&gt;<strong><em>before all other stylesheets to load their CSS.</em></strong></p><p>Some of Bootstrap’s components require the use of JS to function. <strong><em>Place the</em></strong> &lt;script&gt;<strong><em>s near the end of your public/index.html file, right before the closing</em></strong> &lt;/body&gt;<strong><em>tag, to enable them.</em></strong></p><h4><strong>8. CREATION OF COMPONENTS</strong></h4><p>We will start with the four main components, and we will add more later. These components will contain the list of movies, the list of genres, a form to add a new movie and a form to add a new genre.</p><p><strong><em>Inside our client/src/components folder create four files</em></strong></p><pre>touch NewMovies.jsx<br>touch NewGenre.jsx<br>touch MoviesList.jsx<br>touch GenresList.jsx</pre><blockquote>When creating a React component, the component’s name MUST start with an uppercase letter.</blockquote><p>In each of these components, write the following code. Change the name of the function to the name of the file. This is a convention. Write anything you want inside the div. In my example, I just wrote the same name.</p><pre>export default function GenresList () {<br>   return (<br>      &lt;div&gt;Genres List&lt;/div&gt;<br>   )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*aYusmI1yhXyNE9DK" /></figure><p><strong><em>Now, inside your components/App.js change the previous text by the components and import them. See how it should look.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*YQdr8pNlMWcqLqFH" /></figure><p><strong><em>Wrap the NewMovie and NewGenre component in a div with a className=”add_movie_and_genre” It’s a matter of how the styling is defined.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*LzJVmMUoEGkv0S80" /></figure><p>We have now created our main components and we can see them at localhost:3000 Play with the text inside the &lt;div&gt;s and see how it changes. Let’s now work with the first operation of our application, <strong>read</strong> the list of movies.</p><p>Time to commit and push changes? Sure, go ahead!</p><h4><strong>9. BRANCHES</strong></h4><p>Before we start working on our MoviesList component (and our App.js file) we are going to use a new branch. If you already know about branches, or prefer to just continue developing the app, <a href="#75e9">skip to the next chapter.</a></p><blockquote>Use a branch to isolate development work without affecting other branches in the repository. Each repository has one default branch, and can have multiple other branches. You can merge a branch into another branch using a pull request.</blockquote><blockquote>Github Docs</blockquote><p>Let’s play a little bit with branches so you can get a glimpse of the possibilities of using them.</p><p>In your terminal, inside your movies folder, enter the command git branch. You probably will see only one branch, named master or main.</p><blockquote><a href="https://www.theserverside.com/feature/Why-GitHub-renamed-its-master-branch-to-main">Read</a> why GitHub renamed its master branch to main?</blockquote><p><strong>Create a new branch</strong></p><pre>git checkout -b feature/readmovies<br>git branch</pre><p>As you can see, we now have two branches. With the instructions we entered, we created a new branch and checked out (moved) to it. Now, we have two branches with two identical copies of our app.</p><p>Let’s do some changes so each branch contains different versions of our App.</p><p><strong><em>Inside the components, change the text within the </em></strong><em>&lt;div&gt;</em><strong><em>s. Save, commit and push the changes. Since we are in a new branch, git push will not work, you will need to us.</em></strong></p><p>​​git push — set-upstream origin feature/readmovies</p><p>See how it looks, and how your terminal informs you how git push does not work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Cds7vU6EoAlpf2B9" /></figure><p>Have a look at your app in localhost:3000 and see the changes you have made to the components.</p><p>Now, let’s go back to our main branch. See how very rapidly the files in your code editor and, therefore, your front-end , change back to how they looked in the main branch.</p><p>Now, you have two different copies of your app in two branches. We will now learn how to merge two branches. Assume we have finished working on the feature/readmovies branch and we want the main branch to be identical to it.</p><p>If you are not there (git branch), change to the master/main branch.</p><p>git checkout master</p><p>Merge from the feature/readmovies branch.</p><p>git merge feature/readmovies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*qIPNaHf87G0WezXx" /></figure><p>Now, both branches are identical again. Open as many branches as you want. We will use one for each CRUD feature in this tutorial. Let’s now branch again to feature/readmovies:</p><p>git checkout feature/readmovies</p><h4><strong>10. ADD FUNCTIONALITY TO COMPONENTS — READ</strong></h4><p><strong>10.1 Read list of movies</strong></p><p>Our app does not look as much just yet. Do you remember those movies that we created in our database? Let’s show them in our front-end .</p><p>The first step is to create a table to display the list of movies. Replace the content of the MoviesList.jsx component with this code:</p><pre>export default function MoviesList () {<br>  return (<br>    &lt;&gt;</pre><pre>&lt;div className=&quot;tabletitle&quot;&gt;<br>      List of movies<br>    &lt;/div&gt;</pre><pre>&lt;table className=&quot;movielist_table&quot;&gt;<br>      &lt;thead&gt;<br>        &lt;tr&gt;<br>          &lt;th&gt;Title&lt;/th&gt;<br>          &lt;th&gt;Year&lt;/th&gt;<br>          &lt;th&gt;Genre&lt;/th&gt;<br>          &lt;th&gt;Imdb&lt;/th&gt;<br>          &lt;th&gt;Edit&lt;/th&gt;<br>          &lt;th&gt;Delete&lt;/th&gt;<br>        &lt;/tr&gt;<br>      &lt;/thead&gt;</pre><pre>&lt;/table&gt;</pre><pre>&lt;/&gt;<br>  )<br>}</pre><p>See our localhost:3000. We have a table! Well, at least we have a table head. See where we are going? Cool.</p><p>Ugly, eh? Yeap, not an artist writing this article. Feel free to play with the App.css file if you feel comfortable with it. And send me your beautiful styling to replace my ugly boring one!</p><p><strong><em>Now we will add a table body with some fake information.</em></strong></p><pre>export default function MoviesList () {<br>  return (<br>    &lt;&gt;</pre><pre>&lt;div className=&quot;tabletitle&quot;&gt;<br>      List of movies<br>    &lt;/div&gt;</pre><pre>&lt;table className=&quot;movielist_table&quot;&gt;<br>      &lt;thead&gt;<br>        &lt;tr&gt;<br>          &lt;th&gt;Title&lt;/th&gt;<br>          &lt;th&gt;Year&lt;/th&gt;<br>          &lt;th&gt;Genre&lt;/th&gt;<br>          &lt;th&gt;Imdb&lt;/th&gt;<br>          &lt;th&gt;Edit&lt;/th&gt;<br>          &lt;th&gt;Delete&lt;/th&gt;<br>        &lt;/tr&gt;<br>      &lt;/thead&gt;</pre><pre>      &lt;tbody&gt;<br>   <br>          &lt;td&gt;Forrest&lt;/td&gt;<br>          &lt;td&gt;1994&lt;/td&gt;<br>          &lt;td&gt;Drama&lt;/td&gt;<br>          &lt;td&gt;http://www.etcetcetc&lt;/td&gt;<br>          &lt;td&gt;Edit button&lt;/td&gt;<br>          &lt;td&gt;Delete button&lt;/td&gt;</pre><pre>      &lt;/tbody&gt;</pre><pre>&lt;/table&gt;</pre><pre>&lt;/&gt;<br>  )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*6Swy4PPClVJhqYwu" /></figure><p>Good. We don’t want exactly that, though. We want our front-end to do an http request to our back end, which will then <strong>instruct</strong> the database to <strong>get</strong> the list of movies to show in the front-end .</p><p>We will begin by writing the routes and the queries in our back end. The idea is to show all the information from the movies table of our database (query) in localhost:8001/movies (the route).</p><p><strong><em>Let’s go to our server/index.js and write our first route and our first query</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*IJp1j8SOGOcZEtiX" /></figure><p>Let’s break this down.</p><p><strong>Get </strong>represents the http request, the R (read) of our CRUD operations.</p><p><strong>/movies</strong> is the route.</p><p><strong>req, res</strong> (request, response) represent the request from the client side and the response we are going to send back.</p><p><strong>async, await </strong>help us to do an asynchronous requests</p><p><strong>try, catch </strong>makes our error handling easier.</p><blockquote>If some experienced eyes see my previous explanation, I apologize for any incongruences!</blockquote><p>Let’s talk about our query. It looks a bit more complicated than the SELECT * FROM MOVIES, or SELECT * FROM GENRES that we used when creating our database. Let’s see why and break down the query.</p><p>In our front-end table, we would like to show the title, year, genre and imdb of the movies. However, if you remember, the genre_title (in this case ‘Drama’) is in the table GENRES, while the title, year and imdb are in the table MOVIES.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*HJJ1mtZaPxu6ZBDX" /></figure><p>What we are doing with this query is joining the tables. Specifically, this gets done in this part of the query movies JOIN genres on genres.genre_id = movies.movie_genre_id</p><p>See the relationship as we created it in our tables.sql file (line 13)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/0*ydVWaGV-HE1Tzdpp" /></figure><p>I decided to use ORDER BY movie_id DESC at the end of the query, so the latest movie added to the list, is shown on top of it.</p><p>The json() method of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response">Response</a> interface takes a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response">Response</a> stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a>.</p><p>English translation, please?</p><p>This method gets the response and translates it into human-readable. Visit localhost:8001/movies and see the list of movies, as an array of objects. In the future, you will be able to see all the movies that you add to the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*lNIW4-RKcAvNLFQV" /></figure><p>We will now be working in our App.js file and will be using the following <em>technologies</em>: UseState and UseEffect (two React hooks) and Axios (A JavaScript library).</p><p>Hooks are a key concept in modern react. We (remember, I’m also still learning) should aim to know more about them. I will use short definitions for this article but I suggest you read more about them and see examples of people using them.</p><p><strong><em>Import these hooks and library and copy the code below (inside your function App, but before the return).</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*j9zt_7cygew01o0Z" /></figure><pre>---More code above---</pre><pre>import { useState, useEffect } from &#39;react&#39;;</pre><pre>import axios from &#39;axios&#39;;</pre><pre>function App() {</pre><pre>const [ movies, setMovies ] = useState([]);</pre><pre>useEffect(() =&gt; {</pre><pre>axios.get(`http://localhost:8001/movies`)</pre><pre>.then(function (res) {</pre><pre>setMovies([...res.data])</pre><pre>})</pre><pre>}, [])<br></pre><pre>---More code below---</pre><p>The useEffect Hook allows us to perform side effects in your components.</p><p>Some examples of side effects are: fetching data, directly updating the DOM, and timers. In our code, by using an empty array [] as the second parameter, we make sure the effect runs only on the initial render. Otherwise, an infinite loop will be created.</p><p>Axios is a promised-based HTTP client that will help us do the CRUD operations.</p><p>Let’s sum up what we are doing with these two hooks and the library.</p><p>useEffect runs (only once, upon rendering the page) the axios<strong> get request</strong> to our backend. It gets the response (remember, the array of objects representing the list of movies) and sets the state of the variable movies to the data.</p><p>In other words, if we console.log(movies) after the useEffect, we will see in our browser’s console the list of movies.</p><blockquote>Try it. In your browser, go to the inspect/network tab. See how, if you remove the comma and the empty array from your UseEffect hook, it causes infinite renders. Add the comma and the empty array and save the file in order to stop the renders before everything crashes!</blockquote><p>The useState hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.</p><p>English, please?</p><p>We have declared a movies variable and a setMovies function to change the variable movies. In our app, the movies variable will change (when we add, edit, and delete movies) and we need to track it in order to render the updated list.</p><blockquote>What was the state of movies before the change? Actually, it was empty. See the empty array within the parentheses useState([]). Yeap, empty.</blockquote><p>Ok. Nice. We call our backend, which instructs our database, which sends back the information and sets the state of the movies variable. But, I don’t see anything happening in the front-end . Manuel, do I have to just trust you on this? Well, just bear with me for a little longer. We are almost there.</p><blockquote><em>“We call our backend, which instructs our database, which sends back the information and sets the state of the movies variable”.</em></blockquote><p>We now have the movies in our App.js, but we want to show them in our MoviesList.jsx component.</p><p>Let’s <strong>pass them down as props</strong>. Props (properties) are arguments passed via HTML attributes into React components.</p><p>See how it works.</p><p><strong><em>App.js</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*C68nOlAfswNsPOhc" /></figure><p><strong><em>MoviesList.jsx</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*1oCLVtvlV1GxHCww" /></figure><p>Now, we have access to movies within the MoviesList.jsx component. Do a console.log to see it in your browser’s console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*9PBeMOmrVdng67PJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Iv23snzx9aWW7pxo" /></figure><p>Once we have access to the movies, we will replace the hard-coded movie with the movies. To do that, we will use the map method.</p><p>In your MoviesList.jsx component, within the table we created earlier, add the table body and map through the movies variable to obtain the required information.</p><pre>return (</pre><pre>  &lt;&gt;</pre><pre>  &lt;div className=&quot;tabletitle&quot;&gt;</pre><pre>   List of movies</pre><pre>  &lt;/div&gt;</pre><pre>  &lt;table className=&quot;movielist_table&quot;&gt;</pre><pre>   &lt;thead&gt;</pre><pre>    &lt;tr&gt;</pre><pre>      &lt;th&gt;Title&lt;/th&gt;</pre><pre>      &lt;th&gt;Year&lt;/th&gt;</pre><pre>      &lt;th&gt;Genre&lt;/th&gt;</pre><pre>      &lt;th&gt;Imdb&lt;/th&gt;</pre><pre>      &lt;th&gt;Edit&lt;/th&gt;</pre><pre>      &lt;th&gt;Delete&lt;/th&gt;</pre><pre>    &lt;/tr&gt;</pre><pre>  &lt;/thead&gt;</pre><pre>  &lt;tbody&gt;</pre><pre>  {movies.map(movie =&gt;</pre><pre>    &lt;tr key={movie.movie_id}&gt;</pre><pre>     &lt;td&gt;{movie.movie_title}&lt;/td&gt;</pre><pre>     &lt;td&gt;{movie.movie_year}&lt;/td&gt;</pre><pre>     &lt;td&gt;{movie.genre_title}&lt;/td&gt;</pre><pre>     &lt;td&gt;&lt;a href={movie.movie_imdb} target=&quot;_blank&quot;&gt;View&lt;/a&gt;&lt;/td&gt;</pre><pre>     &lt;td&gt;Edit button&lt;/td&gt;</pre><pre>     &lt;td&gt;Delete button&lt;/td&gt;</pre><pre>    &lt;/tr&gt;)}</pre><pre>  &lt;/tbody&gt;</pre><pre>&lt;/table&gt;</pre><pre>&lt;/&gt;</pre><pre>)</pre><p>The ​​key={movie.movie_id} is necessary to avoid this warning in our console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*wsGfb1BiY480KLAR" /></figure><p>Our front-end should now be rendering the list of movies!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*f7y7gPz32FDT2tp0" /></figure><p>Let’s commit and push those changes. Then, you can check out to master/main branch and merge the changes from feature/readmovies or branch from this one to a new feature/readgenres branch.</p><p>git checkout -b feature/readgenres</p><p><strong>10.2 Read list of genres</strong></p><p>We now will render the list of genres in our GenresList.jsx component. The steps are exactly those we did in order to render the list of movies, so this chapter will have fewer details than the previous one.</p><p><strong><em>Try to do it on your own, following the steps from the previous chapter. Read below to get some guidance if necessary.</em></strong></p><p><strong><em>GenresList.jsx</em></strong></p><ul><li>Add the table and the table head with the title of the genre. So, this table will only have a column.</li><li>Add the body with some hardcoded information. Comedy, for example.</li></ul><p><strong><em>Server/index.js</em></strong></p><ul><li>Write the route and the query to get all genres.</li><li>Let’s use the route “/genres” and a simple SELECT * from genres; as the query.</li><li>Confirm that we can get the array of objects from our database seeds on localhost:8001/genres.</li></ul><p><strong><em>App.js</em></strong></p><ul><li>Declare a variable genres and use useState to change the state (const [genres, setGenres] = useState({}).</li><li>Use useEffect, Axios and set the state of the genres to the data of the axios response.</li><li>Pass down the genres as props to the GenresList component.</li></ul><p><strong><em>GenresList.jsx</em></strong></p><ul><li>Bring the genres from the App component export default function GenresList ({genres}).</li><li><strong>Do not forget the curly brackets</strong>. I’ve spent countless hours looking for bugs in my code until I realized I was missing those brackets.</li><li>Add the table body. Map through the genres and get the information. Don’t forget the unique “key” prop.</li></ul><p>Your app should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*IpNlfbpuBagOQdH4" /></figure><p>Commit and push your changes. If you want, merge the branch to master/main or branch off to a new feature/delete branch. In the next step, we will take the necessary steps to delete movies and genres.</p><h4><strong>11. ADD FUNCTIONALITY TO COMPONENTS — DELETE</strong></h4><p><strong>11.1 Delete a movie</strong></p><p>Let’s work on the D of our CRUD application.</p><p>Our app has a very nice (ironic mode: on) “Edit button” and an even nicer (ironic mode: still on) “Delete button”. In fact, these are not even buttons. We just named them that way.</p><p>Let’s actually transform them into buttons and add the functionality to delete the movies or the genres. In addition, we will make sure the updated list is rendered. We will use the state for this, instead of refreshing the page. Cool, uh?</p><p>We will begin with the delete button in the MoviesList component.</p><p><strong><em>First, create the button and give it an onClick event to a deleteMovie() function (that we haven’t yet implemented) taking the id of the movie as a parameter.</em></strong></p><pre>&lt;td&gt;</pre><pre>&lt;button className=&quot;button_delete&quot;</pre><pre>onClick={() =&gt; deleteMovie(movie.movie_id)} </pre><pre>&gt;</pre><pre>Delete</pre><pre>&lt;/button&gt;</pre><pre>&lt;/td&gt;</pre><p>Our browser will alert us that the deleteMovie function is not defined. We do have a button, but it does not do anything yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*TAFmoIKoAKZmghqF" /></figure><p><strong>We’ll define this function before the return statement</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*K8u7KXxW3JrJhrD1" /></figure><p>As you can see, the function deleteMovie takes an id and returns an Axios http delete request to the backend, following the route we defined.</p><p>Then, we change the state of movies to be the list of all the movies that do not have the id that we deleted (see the setMovies with the filter method). This causes the rendering of the new list of movies without needing to refresh the page.</p><blockquote>Don’t forget to import Axios and pass the props from the App.js to the MoviesList.jsx</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*FIhRmU5PgEdLriqh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*dmKnOfhLBBzq33IG" /></figure><p>Hey! Nothing is happening. And I’m getting these errors on my browser’s console!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*Z5NAKwneN0NIhiwH" /></figure><p>Well, we haven’t done anything to our backend yet. In a previous activity, we first set up the routes and queries, and then we did the front-end . This time, just to use a different approach, we are leaving the backend for the end.</p><p><strong><em>In our server/index.js file add the routes and queries to delete movies:</em></strong></p><pre>//Delete a movie</pre><pre>app.delete(&quot;/delete/:id&quot;, async (req, res) =&gt; {</pre><pre>  try {</pre><pre>   const id = parseInt(req.params.id);</pre><pre>   console.log(&quot;Deleted movie id:&quot;, id);</pre><pre>   const deleteStep = await pool.query(</pre><pre>     &quot;DELETE FROM movies WHERE movie_id = $1 RETURNING *&quot;, [id]</pre><pre>   )</pre><pre>   res.json(&quot;The movie was deleted&quot;)</pre><pre>  } catch (err) {</pre><pre>    console.error(err.message)</pre><pre>  }</pre><pre>})</pre><p>By now, you are familiar with this code. There are a couple of new important things to mention.</p><p>First, we have a variable const id = parseInt(req.params.id)</p><blockquote><strong>req.params</strong> is an object of the req object that contains route parameters. If the params are specified when a URL is built, then the req.params object will be populated when the URL is requested.</blockquote><p><strong>In other words</strong>, when the localhost:8001/delete/:id url is requested, the req.params object will be populated with the id, as a string. We use parseInt to transform it into a number.</p><p>The second thing that we will talk about is the query. It looks a little different than usual. For this query we are receiving information from the front-end , from the users. In order to avoid malicious behaviour, such as code injection attacks, we set up placeholders. In this case, when running the query, $1 will be replaced by id. We can, and we will, have multiple placeholders. We would then use $2, $3, etc. This action is also known as sanitizing the database.</p><blockquote><strong>Code injection</strong> is the exploitation of a c<a href="https://en.wikipedia.org/wiki/Computer_bug">omputer bug</a> that is caused by processing invalid data. The injection is used by an <a href="https://en.wikipedia.org/wiki/Hacker_(computer_security)">attacker</a> to introduce (or “inject”) <a href="https://en.wikipedia.org/wiki/Source_code">code</a> into a vulnerable computer program and change the course of <a href="https://en.wikipedia.org/wiki/Execution_(computing)">execution</a>. The result of successful code injection can be disastrous, for example, by allowing computer viruses or computer worms to propagate.</blockquote><blockquote><em>Wikipedia</em></blockquote><p>A related joke. Sorry, I haven’t found the author for credits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*NI5nFajmbM3K_dQj" /></figure><p><strong><em>Ok. Now, try to delete a movie. It’s gone!</em></strong></p><p><strong><em>Now, try to delete the remaining movie. Gone!</em></strong></p><p>Your list of movies is now empty. Do you want to see it again? Well, we don’t have a way of adding movies just yet. But we can use our terminal and PostgreSQL. We could INSERT new movies each time we delete them playing but, you know, we are lazy.</p><p>That’s why we created our .sql files.</p><p><strong>From our terminal, if you are not there yet, enter PSQL and move to our database.</strong></p><pre>PSQL</pre><pre>\c movies</pre><pre>\i database/tables.sql</pre><pre>\i database/seeds.sql</pre><p>Refresh your browser. The movies are back!</p><p><strong>11.2 Delete a movie</strong></p><p>As we did earlier, we will have fewer instructions for this functionality, since it is similar to the delete a movie we just did. Try it on your own.</p><p>Use this guideline if you need to:</p><p><strong><em>GenresList.jsx</em></strong></p><ul><li>Create the button with the onClick event to a deleteGenre() function.</li><li>Pass the setGenre from the App.js down to this component.</li><li>Import Axios.</li><li>Define the function.</li></ul><p><strong><em>Server/index.js</em></strong></p><ul><li>Write the route and the query. The route /delete/:id is already being used. Let’s use /genres/delete/:id</li><li>Don’t forget to sanitize your query!</li><li>Try to remove a genre.</li><li>Did you delete them all, or want all of them back?</li><li>In your PSQL terminal type</li></ul><pre>\i database/tables.sql</pre><pre>\i database/seeds.sq</pre><p>This is what our app looks like at this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*oHnxFfv6_LWqHIVs" /></figure><blockquote>Notice that, if you have a movie and you delete the genre, the movie is still on the list. Let’s solve it by adding an http request to reset the movies.</blockquote><p><strong><em>Add </em></strong>genres <strong><em>to the empty array inside the first useEffect of your App.js file</em></strong></p><p>The deleteGenre function would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/0*qU2fIC1n5Eo5UzMk" /></figure><p>Commit and push your changes. Merge branches if you prefer. Create a new branch or continue working on the same one. Your call!</p><h4><strong>12. ADD FUNCTIONALITY TO COMPONENTS — CREATE</strong></h4><p><strong>12.1 Add a movie</strong></p><p>We will now tackle the C of our CRUD application. Instead of having a form to add a step directly on our main page, we will have an Add Button that will open a Modal. It’s just nicer and it allows us to learn more cool stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Mx6fV0_MZk9E_sva" /></figure><p>This time, we will start with the back end, and then work on the front-end .</p><p><strong><em>In our server/index.js, create the route and query to add a movie.</em></strong></p><pre>app.post(&quot;/movies&quot;, async (req, res) =&gt; {</pre><pre>   try {</pre><pre>     const {movie_title, movie_year, movie_genre_id, movie_imdb} =        req.body;</pre><pre>     console.log(&quot;reqb body&quot;, req.body)</pre><pre>    const newMovie = await pool.query(&quot;INSERT INTO movies    (movie_title, movie_year, movie_genre_id, movie_imdb) VALUES($1, $2,   $3, $4) RETURNING *&quot;, [movie_title, movie_year, movie_genre_id,   movie_imdb])</pre><pre>     res.json(newMovie.rows[0])</pre><pre>   } catch (err) {</pre><pre>console.error(err.message)</pre><pre>   }</pre><pre>})</pre><p>You are now even more familiar with this piece of code. You can see the route /movies, the type of http request (post, this time) and even the placeholders for security.</p><p>However, we see for the first time req.body. We did talk about it earlier, though.</p><blockquote>When you are building a full stack application, you need to get data from the client side (for example, we will be entering in some form the name of a movie). The way we do it is with the request.body object (we will be referencing this a lot in the next steps). We use the express.json middleware to do so.</blockquote><p>Sounds familiar?</p><p>We are going to get from the front-end certain data (name of the movie, year, etc.) as req.body and we will save this information as variables that we can use in our query. <strong>From the front-end to the backend <em>(</em></strong>req.body)<strong> and from the backend to the database </strong>(query)<strong>.</strong></p><p>Now, let’s move to the front-end. To our NewMovie.jsx component.</p><p>We will first place the modal, without any functionality. So we can see how it looks. You can get your modals from this link: <a href="https://www.w3schools.com/bootstrap4/bootstrap_modal.asp">https://www.w3schools.com/bootstrap4/bootstrap_modal.asp</a></p><p><strong><em>For this activity, though, copy and paste this modal:</em></strong></p><p><a href="https://gist.github.com/manuelcasanova/31ad1e0ddcf0f1d7dbf5ec13f2957fd5">https://gist.github.com/manuelcasanova/31ad1e0ddcf0f1d7dbf5ec13f2957fd5</a></p><p>It has two main modifications: the classNames for styling and a key feature of modals. The data-target and the id need to match, and they have to be unique, in order to differentiate them from other modals. I’ve done that by using the movie_id (see lines 9 and 13). In order for this to work we need to pass down movies from App.js to NewMovie.jsx as props.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*S7JXocwu7_UsWYsK" /></figure><p>Our app now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*kb-RDv5rnDcurAL3" /></figure><p>And when we click on Add movie we can see the modal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*IejoX4Tw-J5TtodH" /></figure><p>Now, we will work with the functionality.</p><p>For each of the four fields that we use to create a new mode (title, year, genre and Imdb) we will have a piece of state. When we change something in these fields, the state will change. Then, we will use state in our function to add a new movie.</p><p><strong><em>Import useState in our NewMovie component and declare a variable for each field.</em></strong></p><p>For each field, declare the value as the state variable and an onChange event to set the state to the value of the field (represented by e.target.value).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*Bf-sY6g_csF6qWAp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*um_j4UjKNk2e4s_z" /></figure><p>You can see how, in the modal form, we do not have access to the genres in the drop down menu. Let’s do it by using the map method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ap_AE1_NZzpJpVr3" /></figure><blockquote><strong>Important! </strong>We will need to pass the genres variable from App.js to NewMovie.jsx</blockquote><p>Now, you can see the genres in the dropdown menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*d1AGGtDIqFdIzLzL" /></figure><p><strong>There’s a key thing happening here.</strong> The name that we see on the dropdown menu comes from the line 56 (genre_title), but the actual value is the id (line 55). Remember that our movies table does not include a genre title. Fortunately, it includes a movie.genre_id, which is connected to the table genres.genre_id. This way, we can add a new movie with a genre_id (an integer) while the user actually sees the title of the genre.</p><p>At this point we can open our modal, fill the fields and select the genre from a dropdown menu. However, the Add movie button has no functionality yet. Let’s work with that now.</p><p><strong><em>Add to the Add movie button an </em></strong><em>onClick</em><strong><em> that calls an </em></strong><em>onSubmitForm</em><strong><em> function</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*hin2uvqpq7KAGTsV" /></figure><p><strong><em>Clicking on the add button will trigger the </em></strong><em>onSubmitForm</em><strong><em> function. We will define this function next.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*NbLxGuy30Sbr77sp" /></figure><p>Many events automatically lead to certain actions performed by the browser. We avoid that by using the preventDefault()<strong> function</strong>.</p><p>The onSubmitForm()<strong> </strong>function creates a movie variable, containing the state of the four fields. Remember how writing information in the fields in the front-end changes the state. Well, here is how that state gets to the variable.</p><p>The next thing that the onSubmitForm does is call another function, addMovie(movie)<strong> </strong>with the movie that we just created as the argument. We will write the addMovie function in a moment.</p><p>The last thing it does is to call the resetForm() function. We’ll soon see what this function does.</p><p><strong><em>Implement the addMovie function</em></strong></p><blockquote>You will need to import Axios and pass setMovies from App.js to the NewMovie component.</blockquote><pre>function addMovie(movie) {</pre><pre>   console.log(&quot;Movie added:&quot;, movie)</pre><pre>   return axios.post(`http://localhost:8001/movies`, movie)</pre><pre>   .then((response) =&gt; {</pre><pre>     const newMovie = response.data;</pre><pre>     const movieGenre = genres.find((genre) =&gt; {</pre><pre>       return genre.genre_id === newMovie.movie_genre_id</pre><pre>     })</pre><pre>     newMovie.genre_title = movieGenre.genre_title;</pre><pre>     setMovies([newMovie, ...movies])</pre><pre>   })</pre><pre>}</pre><p>The addMovie() function takes as an argument the movie variable that we created and does an http post request. The response, an object containing the movie added, is assigned to the variable newMovie.</p><p>A movieGenre variable is declared. It uses the find method to find and return the value from the genres list that passes whose id is the same as the added movie’s genre_id.</p><p>Then, we assign the genre_title of the added menu to the genre_title obtained with the find method.</p><p>Last, we change the state of the movies to be the movies, plus the new movie.</p><p><strong><em>Implement the resetForm() function</em></strong></p><pre>function resetForm() {</pre><pre>   setMovieTitle(&quot;&quot;);<br>   setMovieYear(&quot;&quot;);<br>   setMovieImdb(&quot;&quot;);</pre><pre>}</pre><p>After the movie has been added, the form would still show the data if we clicked on the Add movie button again. By calling the resetForm function, the fields go blank.</p><p>We can now add a new movie!</p><blockquote>There might be several cases in which our app does not work as intended. We are going to focus on one of them. Let’s assume we start with an empty app, or we delete all genres and movies. If we create only one genre and then try to add a step, it will not be possible to provoke an onChange event in the genre field to change the state and, therefore, we won’t be able to add a new step.</blockquote><p>Let’s use this piece of code to automatically assign the only genre_id to the movie_genre_id state. Place it inside your component, before the return. For example, above the onSubmitForm function.</p><pre>useEffect (() =&gt; {</pre><pre>     const foundGenre = genres.find((genre) =&gt; {</pre><pre>       return genre.level_id === movie_genre_id</pre><pre>     })</pre><pre>     if (!foundGenre &amp;&amp; genres.length) {</pre><pre>       setMovieGenre(genres[0].genre_id)</pre><pre>     }</pre><pre>}, [genres])</pre><p><strong>If we add a movie without a year, the app also crashes. Let’s apply a simple solution by adding a default state:</strong></p><pre>const [movie_year, setMovieYear] = useState(19);</pre><p><strong>Modify the resetForm function as well.</strong></p><pre>function resetForm() {</pre><pre>setMovieTitle(&quot;&quot;);</pre><pre>setMovieImdb(&quot;&quot;);</pre><pre>}</pre><p><strong>12.2 Add a genre</strong></p><p>Since adding a new genre will be similar to adding a new movie, we will give fewer instructions. Try it on your own!</p><p>Check the following guidelines if necessary:</p><p><strong>Server/index.js</strong></p><ul><li>Create the route and query to add a genre. Remember that it only contains two columns (genre_id, which is automatically generated, and genre_title).</li></ul><p><strong>NewGenre.jsx</strong></p><ul><li>Add the modal. Use data-target={`#newgenremodal${genres.genre_id}`}</li></ul><p>id={`newgenremodal${genres.genre_id}`}</p><ul><li>Import useState and Axios</li><li>Declare the variable and setState</li></ul><p>Const [genre_title, setGenreTitle] = useState(“”)</p><ul><li>Declare the value as the state variable and add the onChange event to set the state to the value of the field (e. target.value)</li><li>Add an onClick={onSubmitForm} to the Add genre button</li><li>Define the onSubmitForm() function</li><li>Define the addGenre() function</li><li>Define the resetForm()</li></ul><p>At this point, our app looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*5p5DkuhN55nSHYIe" /></figure><p>and like this when we open the modals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*JyOliToFw_yzDR3q" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*zmhvC9P30pgAwbij" /></figure><p>Commit and push your changes. If you want, merge the branch to master/main or branch off to a new feature/editmovies branch. In the next step, we will take the necessary steps to edit the movies.</p><h4><strong>13. ADD FUNCTIONALITY TO COMPONENTS — UPDATE</strong></h4><p><strong>13.1 Edit a movie</strong></p><p>We arrive at the U of our CRUD operations. The last of the four that we will implement.</p><p><strong><em>Inside your client/src/component, create a new component named EditMovies.jsx and export the function with a div.</em></strong></p><pre>export default function EdtiMovies () {</pre><pre>   return (</pre><pre>     &lt;div&gt;Edit&lt;div&gt;</pre><pre>   )<br>}</pre><p>This time, we will import this component into our MoviesList component and place it <em>in lieu of</em> our hardcoded &lt;td&gt;Edit button&lt;td&gt;.</p><p>import EditMovies from “./EditMovies”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*-JDzPBiDRIiy10Ol" /></figure><p><strong><em>Again, we will work first in the backend. In your server/index.js write the route and query to edit (update) the movies.</em></strong></p><pre>//Edit a movie</pre><pre>app.put(&quot;/movies/:id&quot;, async (req, res) =&gt; {</pre><pre>   try {</pre><pre>     const { id } = req.params;</pre><pre>     const {</pre><pre>       movie_title, movie_year, movie_genre_id, movie_imdb } = req.body</pre><pre>       const editMovie = await pool.query(&#39;UPDATE movies SET movie_title = $1, movie_year = $2, movie_genre_id = $3, movie_imdb = $4 WHERE movie_id = $5&#39;, [movie_title, movie_year, movie_genre_id, movie_imdb, id])</pre><pre>       res.json(&quot;Movie was updated&quot;)</pre><pre>     } catch (err) {</pre><pre>       console.error(err.message)</pre><pre>     }</pre><pre>})</pre><p>You are now familiar with the try, catch, req.params and req.body. We are not doing a put http request (instead of get, delete, or post) and in the query we are using the UPDATE and SET words, used for the update operations.</p><p>Go back to our EditMovies component. We will start by writing the modal. Again, you can get the modal from: <a href="https://www.w3schools.com/bootstrap4/bootstrap_modal.asp">https://www.w3schools.com/bootstrap4/bootstrap_modal.asp</a></p><p>For this activity, though, I suggest you copy and paste this modal since it already has a unique id and some class names for styling:</p><p><a href="https://gist.github.com/manuelcasanova/98b00621a81bdcbb5212ac287012bfca">https://gist.github.com/manuelcasanova/98b00621a81bdcbb5212ac287012bfca</a></p><blockquote>Notice how EditMovies is bringing movies as props. Pass it down from MoviesList.jsx</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*46jFtzLQ_qvnHI15" /></figure><p>Our app looks like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*MyYHkDPu2Ocx6gWq" /></figure><p>When we click on Edit a movie, it shows our modal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*xA1_fyGYckWov2P2" /></figure><p>Similar to what we did in the previous modals, let’s take some steps to develop the required functionality.</p><p><strong><em>Give the Edit button in the modal-footer an </em></strong>onClick<strong> <em>event to an</em> </strong>editMovie<strong> <em>function that we will declare in a moment</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*Ks-FqIrVkIb_rxKE" /></figure><p><strong><em>Declare a variable and provide it with a state and a way to change the step (</em></strong>useState<strong><em> hook).</em></strong></p><p>For an editing modal, it makes sense for the default state to be the value of the movie to be edited.</p><pre>import { useState } from &quot;react&quot;;</pre><pre>export default function EditMovies ({movies, movie) {</pre><pre>   const [movie_title, setMovieTitle] = useState(movie.movie_title);</pre><pre>    const [movie_year, setMovieYear] = useState(movie.movie_year);</pre><pre>    const [movie_genre_id, setMovieGenre] = useState(movie.movie_genre_id);</pre><pre>    const [movie_imdb, setMovieImdb] = useState(movie.movie_imdb);</pre><pre><br>---more code below---</pre><p>See how we imported useState and for each of the variables we declare a default state of the movie’s information. Remember how we mapped through the movies in the MoviesList component. Is that <strong>movie</strong> from line 35 in the picture that we have to pass down to this component (line 41 in the picture below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*kI6lrk6VwBODuDmT" /></figure><p>Give each field a value of the state and an on Change event to set the state to the event target value. Don’t forget to map through the genres to get the dropdown menu.</p><blockquote>Yes! You saw it. You will need to pass down the genres as props from the App.js to the MoviesList.jsx and down again to the EditMovies.jsx</blockquote><pre>&lt;input</pre><pre>className=&quot;form-control&quot;</pre><pre>type=&quot;text&quot;</pre><pre>name=&quot;title&quot;</pre><pre>value={movie_title}</pre><pre>onChange={e =&gt; setMovieTitle(e.target.value)}</pre><pre>/&gt;</pre><pre>&lt;input</pre><pre>className=&quot;form-control&quot;</pre><pre>type=&quot;text&quot;</pre><pre>name=&quot;title&quot;</pre><pre>value={movie_year}</pre><pre>onChange={e =&gt; setMovieYear(e.target.value)}</pre><pre>/&gt;</pre><pre>&lt;div className=&quot;level_input&quot;&gt;</pre><pre>&lt;label className=&quot;add_movie_title&quot; htmlFor=&quot;title&quot;&gt;Genre&lt;/label&gt;</pre><pre>&lt;select className=&quot;form-control&quot;</pre><pre>value={movie_genre_id}</pre><pre>onChange={e =&gt; setMovieGenre(e.target.value)}</pre><pre>&gt;</pre><pre>{genres.map((genre) =&gt;</pre><pre>&lt;option key={genre.genre_id}</pre><pre>value={genre.genre_id}&gt;</pre><pre>{genre.genre_title}</pre><pre>&lt;/option&gt;</pre><pre>)}</pre><pre>&lt;/select&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;label className=&quot;add_movie_title&quot; htmlFor=&quot;title&quot;&gt;Imdb&lt;/label&gt;</pre><pre>&lt;input className=&quot;form-control&quot;</pre><pre>type=&quot;text&quot;</pre><pre>name=&quot;title&quot;</pre><pre>value={movie_imdb}</pre><pre>onChange={e =&gt; setMovieImdb(e.target.value)}</pre><pre>/&gt;</pre><p><strong><em>Define the editMovie function that we are calling in the </em></strong>onClick<strong><em> event.</em></strong></p><pre>const editMovie = async (e) =&gt; {</pre><pre>     e.preventDefault()</pre><pre>     try {</pre><pre>       const body = {movie_title, movie_year, movie_genre_id, movie_imdb };</pre><pre>       const response = await fetch(`http://localhost:8001/movies/${movie.movie_id}`, {</pre><pre>         method: &quot;PUT&quot;,</pre><pre>        headers: {&quot;Content-Type&quot;: &quot;application/json&quot;},</pre><pre>        body: JSON.stringify(body)</pre><pre>      })</pre><pre>     } catch (err) {</pre><pre>      console.error(err.message)</pre><pre>     }</pre><pre>}</pre><p>Wait, what’s this? Well, we are learning, right? For this function, instead of using Axios to do an http request, we are using a different method, named fetch.</p><blockquote>To send data, fetch() uses the body property for a post request to send data to the endpoint, while Axios uses the data property.</blockquote><blockquote>The data in fetch() is transformed to a string using the JSON.stringify method.</blockquote><blockquote>Axios automatically transforms the data returned from the server, but with fetch() you have to call the response.json method to parse the data to a JavaScript object.</blockquote><blockquote>With Axios, the data response provided by the server can be accessed within the data object, while for the fetch() method, the final data can be named any variable.</blockquote><blockquote><a href="https://blog.logrocket.com/author/farazkelhini/"><em>Faraz Kelhini </em></a><em>from LogRocket</em></blockquote><p>Now, if you edit a movie and manually reload the page, you will see that the job is done. We want the list of movies to be rendered automatically without a page refresh. We can follow two approaches:</p><p><strong>First approach</strong></p><p>Inside the try, make an axios request to the movies list and change the state of the movies variable to the responses data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*GD-hFUn_R4SYYsfE" /></figure><blockquote>Yes, you should pass setMovies as props from the MoviesList component to this component. Also, you need to import Axios.</blockquote><p>Done! When you edit a movie, it renders the changes automatically without a page refresh.</p><p><strong>Second approach</strong></p><p>Within the try, <em>in lieu of </em>the axios request, create a copy of the edited movie’s body (use the {…} spread operator). Add a key value pair with the movie.id</p><p>Declare a new variable. Use the map method to map through the movies.</p><p>If the id of the movie and the edited movie do not match, return the movie. If they do, return the movie and the edited movie.</p><p>Change the state of the movies to the updated movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*yF3S3SIAP7OCUPx7" /></figure><p>Commit and push your changes. If you want, merge the branch to master/main and/or branch off to a new feature/editgenres branch. In the next step, we will take the necessary steps to edit the genres.</p><p><strong>13.2 Edit a genre</strong></p><p>As we did earlier, we will have fewer instructions for this functionality, since it is similar to the edit a movie we just did. Try it on your own.</p><p>Use this guideline if you need to:</p><p><strong>EditGenres.jsx</strong></p><ul><li>Inside client/src/component, create a new component (EditGenres.jsx) and export the function.</li><li>Import it into our GenresList component.</li></ul><p><strong>Index.js</strong></p><ul><li>Write the route and the query.</li></ul><p><strong>EditMovies.jsx</strong></p><ul><li>Add a modal. Use the data-target={`#editgenremoval${genre.genre_id}`} and the id={` editgenremoval${genre.genre_id}`}.</li><li>Don’t forget to pass the genres as props.</li><li>Give the Edit button in the modal-footer an onClick event to an editGenre function.</li><li>Declare a variable and provide it with a default state (the title of the genre to edit) and a way to change the step (useState hook).</li><li>Pass down the genre, genres and setGenre from the GenresList down to this component.</li><li>Give the only field a value of the state and an onChange event to set the state to the event target value.</li><li>Define the editGenre function. Use the fetch() method or try to use Axios.</li><li>Make sure the list renders without refreshing the page. Use one of the two approaches that we have learned.</li></ul><blockquote>You will notice that, if we edit the name of the genre, it updates the genre but not the name of the genre in the list of movies (if there’s a movie with that genre). We can solve that by adding a fetch request and changing the state of the movies to the response’s data.</blockquote><p>The editGenre function would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/0*JvSEDMpRlyIsQdWj" /></figure><p>Your app looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*fFFRkp862cZBfiCI" /></figure><p><strong>Congratulations! We have just created a full stack application using the PERN Stack and performed CRUD operations on two joint tables</strong></p><h4><strong>14. EXTRAS</strong></h4><p><strong>14.1 Link to Imdb</strong></p><p>I know, you want to link to the IMDb site.</p><p><strong><em>Change this line in MoviesList.jsx</em></strong></p><p>&lt;td&gt;&lt;a href={movie.movie_imdb} target=”_blank”&gt;View&lt;/a&gt;&lt;/td&gt;</p><p><strong>14.2 Navigation bar</strong></p><p><strong><em>Let’s add a simple heading (possibly a future navigation bar) for our application. Create a NavBar.jsx component inside src/components and add this code.</em></strong></p><pre>export default function NavBar () {</pre><pre>     return (</pre><pre>       &lt;div className=&quot;navbar&quot;&gt;My favourite movies!&lt;/div&gt;</pre><pre>     )</pre><pre>}</pre><p><strong><em>Import this component in the App.js.</em></strong></p><p><strong>14.3 Props</strong></p><p>As a beginner, like me, it is common to forget to pass props. Here’s a view of the props by the end of the development:</p><p><strong><em>App.js</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*pO3uv8qt4n09pQe6" /></figure><p><strong><em>NewMovie.jsx</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*B3Z7bT9x7VvKfazd" /></figure><p><strong><em>NewGenre.jsx</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*U835fIpESrsUpnl3" /></figure><p><strong><em>MoviesList.jsx</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*7xeyEQySKBGSxcjD" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*SaUT3ymE6Vtk2ARU" /></figure><p><strong><em>GenresList.jsx</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*qrkAS_BKTlpN1onO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*xchHMB6nKopra5jY" /></figure><p><strong><em>EditMovies.jsx</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*_OkWjlnqKsbEiFGl" /></figure><p><strong><em>EditGenres.jsx</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/0*znBFjZ1gmwiRMe46" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8676582c708" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>