welcome everybody my name is Caleb and this is your 20 hour react all-in-one video this is a collection of 100 react lessons that'll get you from knowing basically nothing to having the skills needed to succeed as a web developer so not only react but many of the surrounding skills you're going to need to succeed now I do understand this is a big commitment so I decided for this I'm going to do an intro video the one you're watching right now which will go over some of the stuff we're going to cover that way you have a better understanding of what you should be able to build once this video is complete however if you just want to skip to the actual content and get started then use the timestamps Down Below in the pin comment or description as well as the chapter markers on the timeline you can use this to jump throughout the video to any sections you might find interesting or jump back to any sections you might need review on so like I mentioned we don't just cover react in the series this is more of a full stack development course with the focus being react so we start with the basics of react this includes understanding the different files when you create a react application understanding what a component is what are props what is State these are the essential pieces of react so these Basics just take about the first five episodes nothing major and then we jump right into design now this isn't a CSS course but we cover some of that because if you want to succeed as a web developer not only do you want to be able to display text on the page and interact with it but you want it to look nice to make this process very easy we introduced a technology called Tailwind CSS Tailwind CSS allows us to easily design our application just by applying classes to our components so we can have a decent looking website without knowing the ins and outs of CSS but the cool thing here is you're not just abstracting away CSS and not really learning the details because every class you use in Tailwind CSS has an Associated CSS property so as you're using this you're starting to familiarize yourself with these different properties and how they can be applied to to make your application look nice so really I see Tailwind CSS as a shortcut to creating really good looking applications but if you wanted you could just take the properties that Tailwind CSS uses and apply those to your application directly hopefully that makes sense and no worries if as I'm saying some of this you're kind of like what when we go through this content it's going to make more sense basically what I'm saying is throughout the entire series I want to approach learning in a way that's going to teach us the principles and the concepts needed to pick up multiple different skills and multiple different Technologies I don't just want to take some Shortcut that's going to basically gloss over a bunch of information sometimes we do import themes and do things to make things easier for us and that's appropriate you're probably going to do that in professional web development but I do try to explain things in detail and understand what we're actually doing Tailwind CSS is one of the approaches to designing your applications and this is more CSS focused and another thing we're going to use later on in the series is material UI material UI allows us to also make pretty looking websites but it is instead focused on components so basically a library of components that we can use in our application so good looking buttons good looking forms good looking tables whatever it may be material UI allows us to do that very easily this tool abstracts away the CSS a little bit more so we're not going to get as much CSS knowledge in this section but it'll allow us to very easily create components for our needs enough about styling because we'll move on to some interesting react challenges one example of this is a form that will pre-fill with data from our state this will allow us to then edit that data within the form and it's a very nice user experience additionally we can do something very similar to create new data in our website so we can have a form to input new values and that'll be saved to our state this is all done within a single page application so it looks like you're just on a single page you're not getting a bunch of page refreshes and it's very fast and interactive for the user as we're actually navigating between different components and different pages you can use react routing which is what the next section of videos is going to be about here's where we learn how we can create a navigation bar with Tailwind CSS having links to different pages on our application we can navigate between these Pages without a page refresh and we can style the currently selected link so that it's a little bit different than the rest of the menu options when we create some kind of theme or some header bar that we want to use on multiple Pages this is going to surround all of our components this will use a concept called props.children which we'll explain later but basically allows us to have a custom theme across all of our different pages by this point we have the basics down we understand the basics of react and styling now we actually start working with real data using apis and data fetching so we talk about various ways of fetching data in this series we start off with just the basic JavaScript fetch later on we use axios we also talk about react query later down the road as well so we built a dictionary this is basically going to consume a dictionary API and allow us to search for various words here we're going to deal with many common problems such as 404s which is what happens when the resource is not found as well as other errors how do you deal with those and display those on the page we do this consuming an API that exists out there on the internet but as I mentioned I want this to be a full stack course which means we talk about the front end and the back end so at this point we actually create our own back end now the question is oh what language do we use what framework and I want to mention that although that is important it's more important to understand the principles because you could easily build a node.js backend or a Django backend to do the same thing so we start with a Django application but later down the road we use a JavaScript backend with next JS so starting off we use Django which is the framework for building web applications in Python so we'll get some experience with JavaScript and react and python for our back end this is going to connect to a database a structured database and then later on down the road we will use an unstructured database with next.js and that's going to be mongodb for those of you who are just really curious about what tools we're going to be covering because I know that's important to some of you so we'll be able to build an API and retrieve our data from the back end which we could then connect to from our front end to display this customer data we can add new data to our database all through our application this actually gives me a chance to talk about one of my favorite features so far which is a really cool edit form that will compare the original data to the new changed data and if they're not the same thing then it will give you the option to save or cancel so now we're not just working with you know basic forms with the submit button but smart forms that actually understand the data a little bit to do this we basically keep two copies of the data the original and then the changed and We compare those so we learn about the proper way to compare objects in JavaScript next up what many of you are going to be excited about which is logging in and logging out the ability to create a user and keep that user logged in throughout the different pages on the application we use Json web tokens for this concept and we use use context a hook and react to maintain that state across our application of course there's various ways and approaches of doing this the way we do it is the basics and you can of course go and learn much more about that as well and I actually will share some resources for that or ideas in the conclusion of this series as well logging in is a little bit more complicated that's where things really pick up because now you have to worry about passing additional information with your requests verifying that information on the back end and using a refresh token to get a new access token every time our access token expires using all the skills we've learned up to this point we start building a crypto tracker this is pretty cool because it has a dynamic drop down so we click it and the values are filled in from an API call to get a list of possible cryptocurrencies from coin gecko this is a popular crypto price tracker selecting one of these will render a price chart with selectable time range to change the way the data is being presented ultimately we create a portfolio calculator which will ask how much you have of each cryptocurrency and display this in a nice pie chart based on value this gives us a lot of good practice with chart.js which is what we use for building these charts as well as data fetching and map and reduce for going through array data and aggregating values for the display at this point I kind of just got bored of looking at crypto and my awful portfolio so we moved on to a New Concept graphql this is an alternative approach to creating an API so instead of a rest API we now have a graphql API we start by consuming existing in graphql endpoints for example SpaceX has a really nice API that you can use and the magic with this is it has a query language that we can use on the front end to say what we want returned so we're not limited to just the basic results that you might expect from a rest API so that's where you get graphql versus something like SQL structured query language basically we have the ability to ask for what we want and get just what we want and again once we understand how to work with that we build our own graphql backend in Django with graphene this allows us to get customers but also nested data such as orders if we want so you get a little bit of experience working with relationships and how to return that information once we get done with the graphql we talk about next JS this is a magical tool that will allow you to statically generate site pages so what does that mean well when you're using react all the stuff is done on the front end after the page is loaded so if you look at the source code I'm of a react application it's bare there's nothing there for SEO and sometimes we have to wait for the loading of the fetch to be done with static site generation we can do a lot of that on build time and have the actual data in the HTML requiring no additional fetch to the back end since it's all done at build time we can just send an HTML page to the client without having to then fetch data afterwards so it's good for SEO it's good for site performance and overall it's just a really cool tool to learn this introduces a lot of challenges with caching and other things so we talk about how to fix all of that and we actually build a JavaScript API that uses mongodb so we build out the full crud capabilities create read update delete which could then in theory be a replacement to our Django back-end we created at the start of the series then we talk about react query which is the next magical tool in our tool belt which basically will help keep the front-end data in sync with the back end and manage the fetching for us so it really simplifies our fetching logic it makes our code way cleaner and it makes the application have a much better user experience super great tool really glad I got to talk about it in the series and it pairs very well with next JS so we talk about that as well that way we can get static data to begin with but then as we add new data we can update that front end right away the final thing we talk about in this series is material UI we take a few sections to create a customer list this will have a button to look at order data and it's all within a nice theme that we can use across all these different pages so just another way to get some more experience designing our applications and then finally in the last video we deploy our application so that anybody on the internet can see it that is The quick summary of everything we're going to talk about in this series I really want to create more content like this so full stack web development definitely let me know as you're watching this anything you would want to know more about drop in the comments section below and definitely feel free to create a comment that will be used to keep track of where you're at you know put your time stamp in there update it as you go let me know your experience and I really am excited for you to go through this material stay tuned for episode one stick with it it's definitely going to be worth your time invested this should give you all the skills you need to get a web development job or excel in your career thank you I'll see you in the next one hello everybody it is Caleb and welcome to your react series I have done two dedicated React videos just to test see what you guys thought one was one of my worst performing videos ever and the other one actually did really well so it told me absolutely nothing so I just decided hey we're going to go through a series covering react some front-end principles including design and maybe some more General web development we might get some back-end stuff and we're going to learn about Tailwind CSS as well so if any of that excites you let's get started so react is a framework to help you build web interfaces Tailwind is a tool to help design interfaces a lot easier and it'll help you learn about General CSS as well these are valuable tools if you want to do web development or maybe you're starting a business and you want to build an app well these are really valuable so many jobs are looking for people who know react so this is a great way to get started in software foreign fly so this is the react website react.js.org react will efficiently update and render just the right components when your data changes so components are sections of code that can be reused and react efficiently uses those to build a web page this is great for single page applications where data may be changing it can easily re-render and update the data without causing a page refresh now the easiest way to get started with react is from the terminal probably jealous of my sweet theme Here and there is a tool called npx which allows to generate a react web page and do many other things but this isn't on your computer by default so to get npx you're going to want to download node.js so you can go with LTS long-term support that's fine or if there's a specific feature you need that's new for some reason you can go with current so once you have this we're going to generate a directory for all of our code so make sure you are in the location that you want to put this directory so I usually put everything in a CS folder and from here you can say npx create which the Cs holder is totally optional and just trying to stay organized here I got ADHD so it's hard create react app is the command and then the name such as hello hit enter and I'll go through making that project for us now this will generate a folder structure so you can read about the folder structure in the documentation of create react app.dev it'll look something like this and the code that we are going to write is going to go inside of this Source directory you can create subdirectories inside source but it is important to know that for faster rebuilds only files inside source are processed by webpack webpack is a tool that'll bundle our project up you don't have to worry about that right now all you really need to worry about is react and getting node.js so we can use npx so you don't have to do anything from this create react app website you don't have to download anything here just a documentation if you want to learn more or follow along with things I'm saying in this series so let's go ahead and go back to the terminal and it gives us a bunch of stuff as well as some commands here that we can run so npm node package manager also comes with node and that's how we're going to run our project now you want to do is you want to open that new directory we created which we called hello in this example you want to open that in a text editor so all of our files are available to us there now you can do this from the terminal with Visual Studio code if you have that set up properly but if not you can just open a text editor and go open that directory so for me I'm just going to say code hello and that's going to open our directory in Visual Studio code now if you want to be able to use that command from the terminal you can go to view command palette and type in path install code command in path alright so far so good now let's take a look at our project we have the source and there's a bunch of files in here we're going to talk about some of these some of these we're not going to use though they kind of give you a little extra more than you need so inside of public there's also some stuff as well there's index.html and this is going to be our actual end result web page HTML is what's sent to the browser of whoever visits our website and this is going to have our metadata about our website and a title that says react app thing saying you need to install JavaScript if you don't and then lastly this div which is where all of our content is going to go inside so everything is going to pop up in here but it's going to magically pop up in there using react so we don't actually have to do anything inside of index.html except modify any of this metadata that we wish what we're actually going to be doing is making code from index.js which is a Javascript file so index.html there is the div called root and then over in index.js you can see that it's grabbing that element with the ID root and that is how it knows to put everything inside of it so that's the only thing index.js is really doing it's just putting our app inside of root now there's one more important file right now and that is app.js so you can see that it's rendering app well that comes from app.js which is a little bit more involved and this is what's going to actually show up in the web page so there's like three layers here it can be confusing at start but the index.html we don't have to touch that javascript's going to put all of the output into the index.html file the first file we looked at was index.js which the only thing it's really doing is rendering the app.js file so some people actually just get rid of one of those and only use one but we're going to keep the exact structure as is so basically our entire app is going to be built inside of app.js here's another example from someone index.js is the traditional and actual entry point for all node apps here in react it just has code of what to render and where to render app.js on the other hand has the root component of the react app because every View and component are handled with a hierarchy in react where app is the topmost component in the hierarchy this gives you the feel that you maintain hierarchy in your code starting from app.js other than that you can have the app logic in index.js but it's sometimes related to conventions followed by the community using the library or framework so pretty much everybody will build inside of app.js even though you technically could do it inside of index.js now we're just splitting hairs for a beginner you probably like I don't even care why are you wasting my time let's just code stuff so we'll get on to the next topic now before we move on just want to give a quick special thank you to our sponsor of this video and thankfully we're not going to have sponsored messages for every video in the series so just uh do do me a favor for this one and watch the sponsor message and check them out and for the upcoming episodes all sponsor free so hopefully that makes your viewing experience better so let's go ahead and clean up our project structure because we're not going to need all of these files so inside a public we can just keep the favicon the index.html I'm going to get rid of this logo and this logo and then inside of source I'm going to go into app.css and just clear this out we're not going to need any of that styling app.js is good we're going to get rid of app test JS and I'm going to get rid of index.css I'm going to get rid of the logo and the report stuff and I think that's good so this is what your file structure should look like roughly and when you delete files you're probably going to have to remove references of them throughout your code so here's what we're going to do we're going to say terminal new terminal and the command to run is npm start when we do this we might get some errors because it's not able to resolve those files that we deleted so we're going to do is we're going to go through our code find the files that are missing and delete them so this is coming from app.js and then these two are from index.js so let's start with app.js and inside of here we don't have the logo so we'll get rid of that line here and save we always want to change our files after modifying them and then inside of index.js we're going to get rid of the report vitals line here and this down here we'll save and we can go back to our web page to see the errors but you can also see them down here in the terminal so logo is not defined inside of app.js so I have something over here I must have missed so line seven the logo we got rid of the logo so we'll just go ahead and delete that and then lastly in index.js can't resolve index.css because we nuked it so we'll go into index.js and remove that import so yeah kind of just chasing around errors there a little sloppy but at this point we should be able to go to our page and it says edit source app.js and save to reload and that is coming from app.js this is literally hard-coded right here so that's not like an error that's what's actually showing up in our application so we could say hello save that and now we see hello and a link to learn react which is also coded in here right here as an anchor tag so that is your introduction quite a lot of stuff if you're new so don't be overwhelmed feel free to watch the video again if you want to familiarize yourself with the different commands and the different files in the next episode we're going to talk a little bit more about our file structure and the different files what each one does and how to just be a little bit more comfortable with this setup hopefully you are excited for episode two please stay tuned and hit the Subscribe Button as we go on our way to a million we got like 510 000 more to go so might take a couple weeks but we're getting there I will have a playlist link down in the pinned comment so this is going to make it so much easier for you to watch through these videos please use that playlist to link and you'll get through this a lot easier so thank you for watching and stay tuned for the next episode foreign [Music] welcome to episode two obviously if you're a total beginner complete Noob you'll want to start with episode one so I'll leave a playlist link down in the PIN to comment this video we're going to go over some more of the essentials to getting started I like to go in a lot of depth and have a really good understanding so if this stuff is review feel free to move on to the next episode but for the beginners out there this video is going to be a really great way to get a better understanding of how things work we are going to get to coding real soon but just be patient because this stuff's going to help throughout the entire series so first thing I want to get a good understanding of the different commands we can issue in the terminal and how they work and then I want to get a better understanding of our file structure and the different files a lot of stuff people just gloss over in other Series so hopefully this is helpful information so first thing it's important to note we are developing locally localhost 3000 this isn't available to the internet yet what we do is we create our application locally and then once we are ready to put this on the internet we use a command npm run build so if you have this terminal here and you're typing nothing actually does anything so if you want to kill this you can do control C I'm on Mac it might be slightly different on Windows but you can figure it out then what we can do is say npm run build and this is going to create a new build directory and these are the files that you would upload to AWS S3 for example for static site hosting this is going to allow us to see exactly what the web page would look like with serve dash s build that's going to serve those built files on localhost as well and it's going to look exactly the same but it's just important to know that there's basically two ways of viewing this npm Run start or npm start this is going to be for local development and then you do npm build to do the final product once you do the build you can test it with the serve command which we just showed so let's go ahead and go back to npm run start just so we can go back to development so let's go to the terminal we'll cancel out of the serving and we'll say npm Run start okay cool and one of the cool things about running it with npm Run start is that any changes will be immediately shown so hello there save and it'll pop up right there so this is great for multi-window development or you could split Visual Studio code off to the left and the browser off to the right which we may end up doing for quick development now we made that new change but the build files these are only generated whenever we run that build command so what that means is even though we made this change to the code if we were to upload these build files to a web server somewhere it would not have that change so you would need to run that build command again so anytime you have changes that you want to finish you'll need to run build make a quick mental note that right before you upload files to the Internet run the build command now I want to talk about these files we have and some other commands you should know about so the first one I wanted to talk about is this package.json which lists out different packages needed for our application so our application is going to depend on code that was written by other people and we can just import those packages into our application you will need to do this if you're opening a new project and you don't have all these dependencies installed what you're going to do is you're going to say npm install and that's going to go through these dependencies and make sure they're all installed so after you're done doing this you're going to get messages about potential vulnerabilities from these packages and a message saying something like up to date so we have already installed all of this stuff the other important file is this package lock.json and going through this this will give the exact versions being used for this application so this will allow people who are also working on your application to be sure that they have the exact same version of any dependencies needed for your application so this package.json kind of gives General guidelines and you can look up these different ways of describing it but basically saying hey this should be at least 13.5 and then the exact version that's being used can be found in the package lock.json now let's just say just for fun we delete this file it'll go off the package.json and pick the exact versions and regenerate that file so if we say npm install it'll go through this and regeneratepackagelock.json now I think it's generally recommended to check both of these into Source control that way everybody knows exactly what versions are being used now the actual dependencies the things that we are installing those you do not have to check into Source control because anybody can download those what exactly do I mean we'll take a quick look at our directory structure and you will see this node modules directory which has the actual installed software this is also able to be generated so we can delete that and now when we say npm install it'll actually go through and reinstall each one of those packages which can take some time depending on what packages are being used but you can see I did it pretty quickly and now we have the node modules directory back so since this can be generated you do not have to check this into Source control you don't need to worry about that unless for some reason you needed like a snapshot of all the different packages being used with their source code which most people are not going to need because you can just download it off the internet so all this talk of what should go into Source control what shouldn't go into Source control you might not even be familiar with Source control and that's fine but basically whenever we're building a project we're going to have some way of keeping track of files and file changes and you can Define which files we want to keep track of and not keep track of in the git ignore so anything inside of the git ignore file is going to be ignored in our source control system which is git so we're going to show a little bit about that here and that's exactly what this 10 over here on the left is talking about Source control 10 pending changes so anything in this list is going to be ignored and you can see here the build is ignored because we can generate that with npm run build this is dot DS store is like a Mac thing that it just spams everywhere the node modules we got rid of that here so that's not checked into Source control and there's a couple of other things in here as well so taking a look at our source control tab you can see all the different changes D is for delete M is for modified so we removed a bunch of files and we modified a bunch of files when we use the npx create react app it also initializes a git repository so we started tracking files from the very beginning so what that means is we can always make these changes and then revert back to them so here's what we're going to do we're going to create a message and we just say a clean initial structure for example so basically just getting rid of extra stuff and it says there are no stage changes to commit so basically it's going to Stage all of the changes and then commit them and you can just say yes and there we go we no longer have that 10 and in our git history you can say git log you can see a clean initial structure followed by the initialize project so that is our commit history now you can push your repo up to GitHub and when you do this the readme file is what shows up on the front page of that repo so from GitHub we can create a new Repository and from here we can give it a repository name such as react and we will make this public and we will not initialize this repository because we already have one so create repository push an existing repository from the command line so we'll copy this stuff and then over from the terminal we can if you have your server running you can just open a new terminal with this but I'll typically do that I'll leave the server running in one of them so we can say npm start on this one and then I can issue commands in the other one and I will paste those lines here and there we go now over in GitHub we have our application do a quick refresh and you can use the same URL if you want to access the code for this series scrolling through here you can see the readme.md that's where this content comes from over in our files so if you want to change that you can go into here and write markdown which I have a video on markdown if you want that's a pretty good summary of all the other files some of the other ones the favicon this is what shows up right here next to the title the Manifest I don't really know a whole lot about the Manifest I think it's used for mobile icons if you save it to your home page or something you can see the different sizes here and what image to use you can see it's referencing the actual logo that we deleted earlier so if you were to make a production application you'd want to make sure this is all up to date robots.txt says how different web scrapers should treat this for Bots and search engines that is and yeah that's pretty much it I think we've covered all of the files see that wasn't so bad a lot better than just jumping into one file and typing stuff not really understanding the context that it fits in so I think this is much better way to kind of understand the whole image first and then we can zoom in and now in the next episode I think we'll be creating our first component which is what react is all about I'm super excited I hope you're excited check out episode 3 playlist link down in the pin comment be sure to subscribe come on guys I'm not begging you but please all right I'll see you in the next one [Music] everything inside of react is designed as a component and these are reusable sections of code that we can sprinkle all throughout our application if you have previous programming experience you might be familiar with a function which is a section of code that can be reused components work in a very similar way in fact we're going to create them as a function the only difference is they are going to return HTML specifically they're going to return what's known as jsx which is slightly different in the context of react but you can think of it as pretty much HTML here's a quick example from the documentation where they put a hello world inside of an H1 but then assign it to a variable it's a syntax extension to JavaScript it allows us to do more advanced things such as templatizing nh1 using a variable this value will be substituted in here is another example where you can actually invoke a function to get a result and then that will be inside of H1 so you can kind of think of it as HTML and JavaScript mixed together and this will ultimately evaluate to HTML so to get started we're going to create our first component only three episodes in didn't take too long and what we're going to do is we're going to have app.js open and inside a source we're going to create a new folder components and say we wanted to build an application for an employee Direct Factory well we might create a component called employee so we'll type out employee dot Js and here is where we are going to Define that component it's going to be built as a function so we'll say function employee parentheses curly braces and then at the bottom of the file we're going to say export default employee and this is going to allow us to easily use the employee component inside of other files now inside of the curly braces we're going to say return and we'll just make an H3 here is an employee and we'll save the way we use this employee component is from another component such as app.js we first import it so we'll say import and then we will say employee from and then inside of quotes the file and this is if you look at the file directory here it's going to be in the same directory Source up a directory components employee.js so what it's going to look like is dot slash to say the same directory and then components and then employee you don't have to put dot JS so we save that and now we can use this inside of our code so instead of this paragraph here we can render our own what looks like HTML employee and the way you close this you can do the closing tag like this or it can be self-closed in this case so we'll say employee and then a slash at the end so we have this running from the terminal still it appears that there's no errors of any kind so let's go check the browser head over to react app and it says here is an employee so basically it's rendering the employee component and that says here is an employee this makes code reuse very easy which is what functions do so what we could do is we could take this line and we could copy it and let's say we wanted to do this like I don't know five times we can save and now we have here is an employee five times if we wanted to change this text we don't have to change it in five locations we can just go to the employee component and change the text and it changes everywhere that component is used so congratulations you made your first component at this point you can put that you are a react expert on your resume just at that point don't tell them where you learned it from because I don't come back to me but maybe by the end of the series you really will be very well experienced in react so let's keep learning and this is just a start you know this is slow it can take time but using these building blocks you can start to build some really cool stuff so let's take a moment to talk a little bit more about jsx and what is returned from a component so our component here returns a single thing and all components are going to have to do that so even inside of app.js there is a single return keyword and then parentheses to group everything together and then there's one parent element here the div so everything has to go inside of a single element like that not only do you have the ability to return jsx or HTML you also have the ability for logic to be inserted inside of your component so I wanted to show an example of that what we're going to do is at the very beginning of function app I actually don't really like the way this is indented I'm going to scoot all of this return over one that's better and then what we're going to do is we're going to say console.log we are about to list the employees so you can put statements why does it indent twice for the function star I don't know I'm using some new uh prettier thing but yeah don't worry too much about the formatting as long as it's pretty readable so you can put statements here inside of the function before the return including creating variables so let's say const show employees and we will set this to false just as an example now what we can do is we can Implement logic inside of the return to check this variable and if it's true we will display the employees otherwise we will not display the employees and you might be wondering like why would you want to do something like this well we're kind of just going through theoretical examples but you know you might have an application to view employees but you have to have a certain permission level you know you have to be like CEO or like C Level but if you're just a peasant you know an intern you don't need to access all the employee information so you might Implement logic like this in the application to view employees so inside of our div we can make a ternary which will return one thing if something is true and return something else if it's false so we'll use curly braces for any time we want to use JavaScript code and it's going to say show employees with a question mark I literally think about that in my head like I'm asking a question do you want to show the employees is show employees true that's how I always remember that the question mark comes first for the longest while I always mix it up and put the colon first when I was a noob but now I'm a seasoned Pro and I never make that mistake so here's what we're gonna do if it's true and I'm going to clean this up so I'm going to get rid of this header I don't really want that I don't want any of this crap actually so I'm just going to clear out all this crap and now all we have is the div if it's true we're going to put out all the employees and then what you do is a colon to say if it's false and in this situation we can just do like a paragraph and say you cannot see the employees so it's complaining and this goes back to that same issue I was talking about before that you have to return a single elements so we need to put all of these employees inside of a single thing so we will say you could say div for example or what you can do is use a fragment which is just these uh less than and greater than signs which don't actually show up as HTML so that works fine and there we go so it compiled successfully a lot of moving around code so make sure it looks like this and now let's go ahead and check the browser you cannot see the employees and that is because show employees is false let's go ahead and set this to true and now when we go over it says here is an employee five times so that's how you can do basic logic and you can do console logs inside of here as well if you wished so you don't just have to do it at the beginning of the function you can say console.log inside the return I think we just need to make these as two separate sections like so and that's what it's going to look like so taking a look at the browser you can check out the terminal so go to console and now in refresh we have we are about to list the employees and inside the return I'm going to fix this error too from the Manifest so we'll go over to manifest.json you could replace this logo or if you don't want to don't all right that looks good and now I shouldn't have that error cool so now we have some logic in our component our app component in a final application this show employees value would be evaluated based on the user who is signed in and their privileges but for now hard coding it is fine so to briefly explain a little bit more about the design of components they are able to encapsulate functionality and the logic they are able to have the content or what ends up being HTML and they can have the design this means that your application is built in these self-sustained components and the different Technologies are not artificially split out across different sections of the application so now you can worry more about what each component does and how it should look and act by itself versus splitting the application up across here is the design here is the functionality of each component and then here is what each component is supposed to say in HTML maybe that point was obvious but I just think it shows a lot about how you design and react when you think about that each component is self-sustained and does all of the stuff then it makes building web applications a lot easier knowing how to approach it you've probably noticed by now that we have component nesting here inside of the app component we have these other components and that's totally fine the child components here don't need to know about the parent component so it's kind of like this nesting system I think of nesting dolls where the main app component contains a component or multiple components in each one of those components can have other components in the next episode we're going to learn about one of the most fundamental things of react which is props and this is how a parent component can give information to the child component to customize how it works or how it is displayed so right now our display for these employees kind of sucks I mean it doesn't say anything about the employees not their name nothing so that's we're gonna fix in the next episode using props stay tuned for that episode and friendly reminder playlist link and the pinned comment hopefully if I remember and I'll see you in the next one [Music] what up it's your boy back at you with another react tutorial this one we're going to be learning about props which is how you pass data from a parent down to a child component in our pathetic setup the way we have it set up is that we have multiple employees inside of this app component so these are our child components I'm going to get rid of these console logs we don't really need those so goodbye let's take a look at our employee component and this is designed to be a template for our different components I had the source control up because I just committed a change so if you want to get right to where I was at the beginning of this video you can go find that commit which is called about to go over props all right so the employee is a template I've used this example before many times on this channel you can think of it as a cookie cutter a cookie cutter isn't a cookie right it makes cookies but each cookie might be a little bit different maybe it's a different type of cookie or maybe different sprinkles for that cookie it's just a template so what that means is if we want to give an employee a certain name we're not going to put that name value inside of this employee component we're just going to keep it very general but we can say that we want to use a name and that's where props comes in so we can say props here if we want to use props we set it as a parameter inside of the employee function and the argument values will come from the parent component so what we could do is we could say employee and then inside of curly braces props dot name so here's how we keep it very general where we say the value that was passed in for the name we want it to show up right here so we'll save and then over in app.js we can give an employee a name by passing it as an attribute so name is equal to Caleb we'll save and let's check out our website it now says employee Caleb so there you go that is your first example of how to use props and it allows us to pass specific values for different variables now you might have noticed that if you don't provide a value it just leaves it blank which in many cases can break the display or just make things a little awkward so we're going to go over how to fix that and we're going to do it with the roll so let's say not only do you have the name but you also have the rule so I'm going to reformat this just a little bit so we're actually returning multiple things so when we want to do this across multiple lines we use parentheses we get rid of the semicolon and we're going to put everything inside of a fragment so we will open the fragment and then close the fragment down at the bottom inside of it we can have H3 employee name and then we could also have a paragraph really the HTML Tags I'm just putting things don't worry about it too much right now you could use a span or make this one an H2 and this one an H3 however you want to do it for now for the paragraph what we're going to do is we are going to say props dot roll and you'll notice that it's no longer highlighted blue because it's not inside of the curly braces so whenever we want to render a value we need to put it inside of curly braces and this will work the same way but I want to condition so that if it doesn't have a role it'll say something like no rule so let's just try it first we'll say role is equal to intern and this way we can just see what it looks like to start with so it'll say employee Caleb intern for these other employees I want to First give them a name and then I want them to say no role so let's go in here and I'll just get rid of two of these to make it a little easier so name is Abby and name is John now inside of our employee we can condition so we can say does this person have a role if so we can return the value of roles so props.roll otherwise we will just say no roll and this we can surround with quotes all right so that should be the structure let's take a look we've got employee Caleb is an intern employee Abbey is no role an employee John is no role now let's talk a little bit about the syntax if you're new can be a little confusing because sometimes we're using curly braces sometimes we're not sometimes we use words by themselves sometimes we put them in quotes and it really depends on the context if you in this case are within directly within HTML tags then you will not put quotes around any strings and any variables are going to be inside of curly braces if you flip it around and this time we are in directly inside a curly braces you do not need to use curly braces For The Individual variables and you do need quotes for any strings so another way you could write this just to try it out is you could say props dot roll put the paragraph on the inside and then inside the paragraph do props.rool otherwise we could do something like another paragraph no roll so in this situation we don't need quotes because it's directly encapsulated inside of a paragraph you could do this either way and the result should be the same the reason why you might want to do the second one is if you want to display something different whereas this one you have to put it inside of a paragraph so for example in this case you could say class is equal to roll and then this one class is equal to no roll you're unable to be that specific if you used this syntax up here I'm going to save it it's probably going to reformat it but it might allow you to see it a little bit better so in this situation it's going to render a paragraph either way but the paragraphs are different in this one up here the paragraph is going to be exactly the same so it's a little simpler so in this situation the parent component is the one responsible for the state the data that's to be displayed and props inside of the child component should not be changed so we shouldn't be in here trying to assign values to props don't try to modify props if you do need to change the value for a property well that's going to be done in the parent component as well so as you get more skill you'll be able to understand how to do that better so we're going to be doing some of that in this series so stay tuned for the next episode in the next episode we're going to learn about Hooks and how the state of the page can be updated react does this very efficiently without any page refresh so it's like things just magically change so that's going to be really cool stay tuned for that episode [Music] good morning everybody it's a new day I'm ready to conquer some new challenges so we're going to be talking about State this is a very important part of react so make sure you pay attention and we just talked about props this video we're going to talk about a little bit of the difference between the two when to use which and yeah I think that's it oh yeah subscribe that's what it was totally forgot so as mentioned in the previous episode props are not meant to be changed to illustrate this let's go ahead and enter this function and we will assign a value to prop star name it doesn't really matter what it is so just go ahead and type something and when we save it'll say compiled successfully going to the browser opening inspect you can see there's nothing showing up here go to console we get a bunch of errors here cannot assign to read-only property name of object and this is referring to employee line two what this means is that we're not supposed to change the value of the props in the child instead we will change it in the parent and the way we're going to change this value is with the use of state state will allow us to keep track of values but it's a little bit different than just a variable because the state can be tied to the user interface so that when the state changes the user interface will automatically update this will be important because we're going to be working towards building an employee list where you can edit people's information and it will update the user interface without a page refresh so to do that we're going to need state so let's go ahead and go back to our code fix it and then I'll show you the better solution on changing values so we'll go over remove this assignment here save taking a look at a browser this is what it's supposed to look like and what I want to do is I want to be able to change these values so we have Caleb Abby and John let's say we have an input so we'll go up here into app.js above our employees we can say input type being equal to text and we will also have an on change property and this will be invoked anytime we change the value so that's what the structure is going to look like and then inside of here we're going to create an arrow function which will allows us to Define it in line which makes it a little easier and we'll say console log now to get what actually is typed in into the input we use e dot Target dot value so we'll save it does a little bit of reformatting so now we have this input and as we type you can see it says e.target.value because I'm a literal and I put it in quotes so word of advice don't be a like me so we'll save that now where does this e come from well it's passed in to the function so we create a parameter on this function and that value will come from this input so now it seems to be working where we get hello there in the terminal we could Define a variable up here we'll just say let roll be Dev and then Abby's rule could be assigned the role variable we save so far so good employee Abby her role is death so let's just go ahead and assign that value to that variable so we can change it right and the actual fix for this because this isn't going to work quite yet but the fix is going to just be a small change which will introduce state so we save and as we type there let's go ahead and say intern you can see it shows up down here in the terminal but the actual value being displayed is not updating even though we set the role to the rule variable and we are updating the rule variable value and that's exactly where State comes in and how it is different than a variable we want to use a variable that is associated with the display on the web page so to introduce State we need to do an import we say import use State inside of curly braces from react now why is this one in curly braces and the employees not well inside of our employee we export default employee the way that you state was exported is a little bit different which requires curly braces not really an essential piece of information to understand right now just know that you have to put the curly braces here it's slightly grayed out because we haven't used it yet so let me show you how to use it you're going to say const and then in square brackets you're going to put the name of the variable so we will say roll comma then you're going to have a function which will allow us to set the role and this is going to come from use state so this is the structure and then we can get rid of this line here anytime you use State it's going to look pretty much like this these are just variables so you can change the names of them but by convention people will usually have the variable and then the variable prefixed with set in cable case now the U State this is going to take any default value so where we used to assign Dev we now put it in here right here we don't need to change role down here because it's already Associated to that variable but you can see the set rule is slightly dimmed because it's not being used we need to use that function instead of assigning it a value number one rule of state is you never assign a value to the variable directly you always go through set whatever the state is in this case set role it's going to look like this we will remove this line and replace it with set role and then pass in whatever value we want such as e dot Target dot value which again gets the value from the input we save and that should be our final code so let's go ahead try it out in the browser So currently it has Dev as default and we could change this to something else engineer and you can see it updates automatically as we type so very cool that is the proper way to work with values that need to be changed on the user interface inside of react now as for the employee component it doesn't do anything to change the value all it does is display the value and that's all it needs to do the parent is the one that controls what is being passed to the employee component it can be a little bit confusing at first especially getting used to the proper syntax on using State and you know understanding which components do what but as you go through more exercises this will become a lot easier now this actually introduced a very important subject inside of react and that is known as hooks so use state is an example of a hook there are other hooks that we can use to introduce functionality into our components very easily so again use state is one and when things start with use it's a good sign that it is a hook we will learn about more hooks in upcoming episodes but when people are talking about hooks that is what they mean this allows you to use other react features without writing a class right now we are using function components another alternative is to use classes but I prefer to use the functions with hooks as do most people in modern react I would say so at this point we have a pretty basic understanding of react but our website has looked like absolute trash so the next episode we're going to learn about the basics of styling with full disclosure that by no means am I a web designer but we're going to try and build something like this alright calm down yes I know it is beautiful but we will do our best to recreate this and this will eventually allow us to go in edit change a name so for example we could change this back down to intern and it'll update the value on the user interface so it might take us a couple videos to get to this point so in the next one we're going to get everything set up so that we can start designing now it's not a design course so we're not going to go in a lot of depth but we'll cover the bare minimum to get it to look at least decent so stay tuned for the next one I'm excited see you then [Music] hello everybody and welcome to the world's first design video from Caleb himself Caleb Curry yes my name last name is curry no I'm not related to Stephen Curry so as mentioned at the end of the last video we're going to be trying to build something like this over the next couple of episodes where you have employees you can go in and edit their data and it'll automatically show up on the web page after you submit there's a lot of different ways you could do this I'm going to show you the quick and easy way without any prior design experience and that is by copying other people kidding but I'm kind of serious because we're going to be using tailwind and they have a lot of good examples that you can pretty much just copy paste in your code modify a few things and what I like about Tailwind is it's not some massive thing you have to learn I was like scared to learn it because I hate learning new Frameworks every five minutes and new things like that but pretty much they just use classes that are directly associated with CSS rules so by learning Tailwind you're also learning plain CSS so nothing new that's magical it's all pretty self-explanatory you just have to combine CSS rules the right way to create something fairly cool and I know this isn't the most amazing beautiful app you've probably ever seen but it's a good start to teach rack principles but man I am talking way too much so let's just jump in and get started how to install Tailwind CSS with a react application so Tailwind has a guide on installing Tailwind CSS with create react app now we already did this step create react app we already did that so now we just have to go down to this step where we install Tailwind so let's go ahead and copy this line here then from our terminal in our project and actually I'm going to commit our changes before installing Tailwind so you can get a fresh start if you've been following along from the beginning of the series playlist link Down Below in the pinned comment so we can get to this point because I'm going to commit this with the message getting ready for CSS so now you can get the exact same files from the GitHub repo which is located right there all right so let's go ahead and install Tailwind go ahead and grab this next line which will initialize some junk specifically tailwind.config.js and post css.config.js pasting that here and now we configure our template paths add the paths to all of your template files and your tailwind.config.js file so from our file list we can go to tailwind.config.js and we can pretty much copy what they have from the install instructions so we'll take this here paste it here safe and this will grab any JavaScript files in any subdirectory of the source folder so it should include our components next up we just have to go in and copy these three lines which will import all the essential Tailwind styling and then all we have to do is run our application like normal and apply classes to things we want to style so we will paste that here in app.css you can also use index.css either one I ended up removing that file so we just have appbox CSS and that is imported into our Javascript file here let's go ahead and try this out we'll just say something background red 300 save I think with installing a new package we will just restart the server and there we go we can now see that there's this light pink background that little white section is the input that's why it looks like it's missing something all right so that is a summary on how to get things installed just a quick review on that all you have to do is after creating your application so you don't have to do anything special when you create it you just install you initialize you say where your JavaScript files are and then you add the Tailwind directives to your CSS I'm just going to make one change and that is just to adhere to the proper naming structure here with index.css it should work fine with app.css because it's a CSS for the outermost component typically throughout react you will see CSS files associated with the component files as well so you can think of these as kind of paired so since I don't need app component specific styling I'm just going to rename this to index.css and then updates our import here to index.css if you just jumped in and you haven't been following along from the beginning of the series then you may have already used create react app and you already have an index.css in that case you can just use that file all right so we have to win installed now let's talk a little bit about how it works put simply Tailwind CSS just abstracts the core CSS rules and replaces them with classes and this makes it a lot easier so for example we could type in to their documentation background color which is the one we just used and it'll give you some class options and the associated CSS properties so for example any of these we could take these CSS properties and apply them to our different elements you can do any CSS file or if you just want to experiment you could go over to your application and paste this in somewhere so let's go ahead and apply it to say this paragraph here you can click that and then in the element style paste that in and that's pretty much it I like this because there's not a lot of magic going behind the scenes you just have to find the right classes to apply to your elements and you can find the exact Associated CSS rules if you wanted to use plain CSS so some other options on here there's borders effects filters tables trans all kinds of stuff on here but you can search pretty much any CSS thing you might want such as display and you can see the different options on here or margin and you can see it's m Dash zero for zero margin or you can replace it with some number and you can see it can be a lot simpler because you can do something instead of margin left this and then margin right that you can just say margin X is one X being the x-axis same thing for the y-axis margin top and margin bottom if you're familiar with flexbox or grid they have all of that on here as well so you can type in flex and you can get some of the examples here once you're done styling on build all of your rules will be transformed into a build.css file so you can see that over in your code if you run npm run build taking a look at our built CSS file it's obviously not quite as pretty as the example they gave but this is going to save on Space you can see our background color right here that's your basic control on getting Tailwind installed inside of a react application the next episode we're going to take some of these classes and apply them to our website so we can get more of that card look with the different employees that's pretty much it so see you in the next one foreign [Music] what's going on everybody it's Caleb in this video we're going to go through some of the examples from the Tailwind website and pull them into our application so the previous video we installed tailwind and got it all set up now we're going to style our application and as a principal don't recreate the wheel if you don't have to so we're going to use some of their examples first off if you want to follow along I got everything committed to this URL right here and the last commit is install Tailwind so let's go ahead and go over to the Tailwind website and you should be able to go to their docs and in here you can find examples so utility first fundamentals scrolling through here you can find some different examples of little boxes and the one we're going for is pretty much this if you remember the example website I showed you it looks very similar so that is exactly what I use as an example so let's go ahead and copy this code here and this is describing how an individual employee is displayed so this is going to go in the employee component so I'll go ahead and actually I'll just remember what we need so props.name and props.rule so I'm just going to completely delete what we have and paste this here and then just go through and clean up some of the formatting that looks a little bit better and then I think it's just complaining about the image because we need to have a closing slash there so we want it to be self-closed save does a little bit of reformatting and now let's just go ahead and replace these values here so we had props.name and then here we had props dot roll there we go so let's go ahead and start our server so npm Run start and here we go here's our site we still have that red background so let's go ahead and delete that we'll go over into app.js get rid of this here and so far it looks pretty good I mean it's not the prettiest thing in the world but we're we're getting there so I'm not going to go over all of the classes but let's just take a look at some of them so you have py that is padding on the y-axis eight this number refers to a certain number of REM so you can go into the documentation and for whatever you're looking for you can just type it in so padding and they'll have examples here so p8 is 2 rem or 32 pixels next up we have the padding on the x-axis we also have a Max width which is small which is a certain size you can look up as well we have margin Auto margin X Auto which will Center it white background rounded edges we have space Y2 which if you're not sure what any of those are you can search by name so you can just say space and space between and then we have space Y2 so margin top is a half Rim now when you see something like SM colon it's saying only on small screens and that's pretty much all I'm going to cover when it comes to the individual classes and we'll cover more as we go on now I'm going to change it a little bit because the way I want it to work is that if we have multiple of these employees it's just going to fill them up throughout the page and as we zoom in it'll fill less of them up on the page so I'm going to do this using the flex keyword and this will use flexbox so going back to app.js we're just going to surround everything with a class name and I guess maybe we won't put it in this most outer div rather just the code surrounding the individual employees so let's go ahead and make a div here and then I will take the closing div put that down here and then everything inside of here is going to adhere to these class rules so we'll say class name and inside here we're going to use two things the first is flex and then the next is flex wrap so we will save this and take a look at our site you can see now it looks a little bit different where these are actually going to go to the next line if they take up the full page so first let's learn a little bit about Flex so what you can do is you can search Flex here and there's two sections for Flex so flexbox and grid flex and then for layout so if you check Flex there's not an option for that so what I'll do instead is go to the layout one and you can see here use flex to create a block level Flex container if we were to remove Flex let's see what that looks like we'll go over to our site and it no longer will display them one after the other to fill the page so we definitely want to have that in there but what about this Flex wrap what will that do well same thing if we don't have it well it's still going to fill them left to right but now if there's too many or not enough room it's just going to squeeze them and push them off of the page so what we wanted to do is if there's not enough room we wanted to drop down to the next line and that's exactly where Flex wrap comes in and you can find that in the documentation as well just search Flex wrap and this will allow items to wrap versus don't wrap even with these changes our site is still awful so let's go ahead and work on some other improvements I think one of the easiest changes we can make is inside of the employees inside of this class we can do m-2 to add a margin so that's going to space out our cards a little bit and that is already looking a whole lot better I think we can fix this spacing here by getting rid of the auto margin so get rid of this line here save check it out now and that looks a little bit better so what we'll do now is we'll add a few more to see if it rolls around to the next page and then we'll try to get an image on here so let's head over to app.js and I'm just going to take these three employees here and copy them like so and now you can see it rolls over let's do one more just to see how it looks with a bunch of them so it's looking pretty good now for the image you can go ahead and get one off of a free website I like pixels.com so the one I'm going to use is this guy right here it looks like Professor X from X-Men but it's this will do so we'll save that image actually you don't even need to save that image you can just use the URL and we're going to go ahead and add a new image attribute to each one of these so let's go ahead paste that URL here and I don't need to worry too much about this finding all unique images because in the next video or the one after that we're going to reformat a little bit how we're doing this so we're working with more structured data inside of an array so for now let's just go ahead and paste this in here a few times all right we'll save that I just did the first three and then I'll go ahead and just copy the first three again so we'll just take this three here alrighty there we go we got a bunch of employees now we should be able to go to our site do a refresh and it's still broken and that's because we need to actually use that image inside of our employee component so here's the source we're just going to change this to props dot image and I'm just going to get rid of the alt save and there we go it looks a little bit better now we still need to make a circle so we're going to do that first and then I want to get them all centered in the page that's a really easy fix so let's just do that real quick inside of app.js we can just say justify Center save and now they are all centered I'll show you the magic to making these perfect circles even though they're rectangle images we're going to go over to the employee and in this image here we are going to add a few classes paste this here so we have object cover rounded Fool by 100 with a hundred save take a look now and there we go we got circles you can look up those classes on the Tailwind docs I'll show you another way just for a little tip if you inspect you can figure out where different CSS properties are coming from based on their class so for example object cover is really doing object fit cover and then rounded full width is 100 pixels and height is 100 pixels now we should have a pretty good responsive application and let's go ahead and actually try it on the mobile so to do that you can open the dev tools hit this little button here it'll show what it looks like on a mobile device that is your basics for this video in the next episode we're going to continue working on this actually try to make it a bit more functional right now it just has the same image for every single one it has a bunch of repeating data it has a message instead of edit so we just still have a lot of work to do and I want to get all the user data from an array of data because that's going to be a more realistic way of how we might work with data know once we have a back end and a database so we got the basic styling and we'll add basic styling as we go just to get things to look the way that we want when you're working with an array it actually gets a little bit more complicated on the react side so I'm going to teach you how you can work with an array properly using State and how to map through those elements so stay tuned I'll see you in the next video [Music] everybody Welcome in this one we're going to be talking about how to work with multiple pieces of data inside of one state variable in other words how to work with arrays or you could say a list of data right now the way our code is is we have multiple of these employee components with slightly different data the end goal is to just display one component but do it inside of a loop and then just substitute these values in from data coming from an array so it's going to cut this whole section down to just a few lines of code and then we're going to move the data elsewhere the data is going to be stored in state but it could be easily substituted out to come from an API so even though we're going to hard code the values into our code right now don't worry about this long term because it can easily be changed out right now how we have it it's not easy to change out because all the data is spread out across multiple components so step one is to take all of our data move it to the top in a single variable step two is to replace displaying those components with a loop using map so that will go through each element in the array and do something with it so let's get started first thing from the top we're going to use a new variable here so we'll say const and this is going to be plural for employees and then set employees use state there we go now inside of the parentheses is where we can define a default value and this is going to be an array of multiple employees and for each element in this array it's just going to be an object that describes that employee so what might this look like if we scroll down and we can compare it to this data here we have name is Caleb roll as intern and then that image so it's going to look very similar but the syntax is a little bit different if you're not familiar with objects so it's going to be Name colon so basically T value pairs here Caleb comma role is going to be let's just go with developer and then lastly we will put the image and I'm just going to copy this URL down here so yes the data is still hard-coded but just as a reminder this is going to be much easier to substitute out later with real data so now that we have that first element we're just going to basically repeat that process for multiple employees so copy the first one and I'm just going to paste a few in here so I'll just go with five for now actually I'll do six and get three per row now I'm going to go off of this example I built earlier so I'm just going to copy their names and their images again you can find images from pixels so I just went on pixels and looked up face and then grab some of the first ones I found or you know if you're working with real data then you can get either the image data or a link to the image so go ahead find some people and let's grab those links so I'm going to start filling these out so I'm just going to copy image address and that'll give me a link to wherever that image is which I'm going to then fill out on this page here and I'm going to give a variety of roles here so manager and also another note on how to actually get the URL for that image from pixels when you grab an image from here you can right click and if you copy image address it's going to include a little bit of extra stuff so I'll show you what that means here you can see this Auto compress and all this extra stuff you can leave that in if you wish but just for what I was doing I just removed any of the extra sizes limitations or compression stuff so I just grabbed the image by itself and that's exactly what I'm going to do for the rest of these so I'll go ahead and fill those out and then we will meet again all right I'm just about to finish up this list and that is now our data now to make sure that this list is working correctly well we can't see it on the web page because you know I'm going off of the example app I made but right now our web page looks exactly the same so we need to try and display that data going down to where we are displaying all these employee components and we're going to just delete them so scroll down delete all this crap now what we're going to do here is we're going to Loop through our state data which is defined as employees so to do this you use the variable name I'm going to zoom in a little bit now since we have some more space employees dot map and this is a function on an array that allows us to go through the elements and execute a function for each one so it's going to be an arrow function inside of the parentheses now the reason we're getting like a syntax complaint is because this is within a div so it's thinking it's just plain text so what we need to do is we need to wrap it in curly braces so that is how you understand this fairly complex syntax and now what we can do is we can expand the curly braces and this is what's going to happen inside of the function and any data that we want to work with is going to go into parentheses here specifically each individual employee is going to be assigned to that employee variable now my formatting software just undid my space so I'm just going to put that back here and we'll just say console.log employee saving this confirming our server is going good we can do a refresh and you can see all of our data showing up here so each iteration we can refer to an individual employee now we only have to do the employee component once inside of this Loop and we want that to be a capital E to refer to our component so employee name is going to be employee dot name so that variable dot name role is going to be employee dot roll and then yep image is going to be employee dot image self-closing beautiful we save does a little bit of reformatting for us with prettier I actually like kind of prefer it all in one line just because I like to use more horizontal Space versus making my file hundreds and hundreds of lines but I think there's a lot of other benefits to prettier just like working with teams keeping your file consistent so I'm still using it for the series so far so what do we have now do a refresh nothing is showing up what's going on well since we are now within a function what we want to show up on the page needs to be put inside of a return so we put return and then surround it with parentheses if it's on multiple lines so that's the Syntax for that save and now I'm going to go back you can see our data shows up at this point if we change the interface essentially for this employee component we only have to change it in one location so for example you could easily add in an ALT for the image you could pass that in here instead of across six different uses of the component plus this can expand to you know potentially hundreds or thousands of employees without any additional code now at this point we can get rid of this console log and also in the employee we're going to update this message button to update in theory that's going to be used to update an individual's information now one more thing I want to say in this video you'll get this warning saying each child in a list should have a unique key prop and what this means is basically react keeps track of all the data on the page and if you were to update a piece of data well it would know exactly which component which piece of data you're talking about that you want updated an ID is a way to uniquely identify each element inside of an array so that when you update you don't have to update the entire page it can just update the specific piece of data that was changed so going back into our code it would be ideal if this had a key attribute and then something to make it unique such as an employee dot ID so what you can do is you can set this to employee ID and then go up here and manually set an ID for each one of these ID and then the value one and then just go through incrementing two three four throughout the rest of your data that's one option a pretty good solution but you may not want to add these IDs that don't really mean anything so here is another option you can actually use a unique ID that's just generated on the fly a grid specifically a grid guid stands for globally unique identifier in our code what we're going to do is we are going to install a package so we'll say npm install uuid which is universally unique identifier same thing once we have that installed we can type here and then we'll show how to import it uuid V4 parentheses save that and we're going to import that from the top here we will say import V4 as uuid V4 from uuid save that there we go that should fix the problem so let's go back to our browser do a refresh and we no longer get the warning about the key now if you wanted to see what this looks like you could just for fun just try it out just console logging it so console.log uuid V4 that's going to show an example of what a uuid looks like however it's not going to be the same value as this one unless you assign it to a variable because it's going to generate a new one but it's going to look something like this so that is your introduction to working with arrays of data the only thing that we didn't cover in this video that I think is really important is adding an element or editing data inside of that array so we talked about how to set it initially and how to display it but we haven't talked about editing or adding to it which we'll be talking about these things in upcoming episodes but I think that's enough for this video to get you started so stay tuned for the upcoming videos if you want to know how to add and edit and my camera just turned off so I appreciate you watching and uh yeah I could be doing anything right now and you can't tell holy crap did you see that oh no you didn't oh no it was crazy well I should probably go take care of that so I'll see you in the next one if I survive see you then this journey is continued in the next video if you would like to follow along please proceed to the playlist link down in the pinned comment and have a great day [Music] hey everybody welcome back to your react Series in this episode we're going to talk about creating a modal this is a pop-up window that goes on top of your web page that you can then interact with or close this is how we're going to edit data that pop-up is going to come up we can edit as much as we want and then it won't change the original data until we hit complete or update or whatever the button might say so let's go through an example of what this might look like here's our application whenever we want to edit some data we can just go in here change it and hit update and it'll replace the data on the home page now if we wanted we could build this from scratch but as you guys know I like to just use what we can out there already that'll make this easier for us so there is what's known as react bootstrap and this will introduce a bunch of components that we can use in our project that Curry media how may I help you as I was saying before us so rudely interrupted react bootstrap gives us components we can use and it makes it very simple so one of these is the modal and we can get a really good example of how to build that functionality into our project and it's not too bad now because we're going to have an edit button for each of the different employees we're actually going to do it within the employee component you could do it inside of there or you could create another component just to manage the modal part of things which I think is what we're going to end up doing now before we jump in the next couple of steps get pretty complex so we're splitting this up into a few different concepts first we will learn how to create the modal with react bootstrap how to open it and how to close it pretty simple once you get the hang of it but it's a little complex if you're new so we'll try to explain it the best of our ability number two styling and submitting with a button number three passing props from an employee to the new modal component that will be basically autofill the user data into that modal and then lastly hitting that update button and having that data change on the home page of our application so with that intro let's get started with getting the modal setup so that it opens and then we can close it so first thing I want to mention is that from the previous videos I renamed these from class to class name which is the proper way to define classes and react so if you've been following along from the beginning make sure you update that to class name that was just a copy pasta error and I'll be careful not do that in the future that being said it seems that the classes were still being applied even though we just use class instead of class name so let's head over to react bootstrap and there is an install guide under getting started so one thing I want to remind you is that nothing is going to look good unless you import the CSS so this is a two-step process not just a single step so if you do this and it looks awful that's probably why so we're going to do the npm install and we'll go down in the terminal paste that there and that will download what we need and add it to our package.json now let's go ahead and grab that CSS copy that and that's going to go in your outermost Javascript file so let's go over into index.js and we can import that here now these Styles should be available to all of our components on our website so for creating the modal we're going to create this inside of a new component so Source components right click new file and for the name here I'm just going to do edit employee and the naming convention here is Pascal case which is capital letters for each word you'll often see lowercase with hyphens between the words as well I wouldn't worry too much about it just be consistent now heading back to the documentation we can search modal and there are a bunch of examples so we will want here's one so let's go through these this one will allow you to click off and that works for many examples I tend to prefer the ones that do not close when you click outside of them because I hate when I'm working on something and then accidentally click or something and it gets rid of my work so this is the one I'm going to use but feel free to use whatever you want from this list but if you want to follow exactly this is what you're going to want so I'm going to copy this code here I'm not going to take the render so just this and then we're just going to go into edit employee paste it and change a few things specifically the name of the function so we'll say edit employee and then this is going to be exported so we'll say export default edit employee which will allow us to bring it into other files now let's see what this thing actually returns if you take a look it returns a button and the modal itself all within a fragment so we don't actually have to create a button ourself although we do already have a button inside of our employee so we're going to talk about what we're going to do with that but for now let's just push our button down and we'll create the new button just by creating an edit employee component and it'll be self-closing so we'll save that and now let's try this out you can see it looks a little bit funny but we're going to make it look a lot better don't worry so we have two buttons now our update button which doesn't do anything and then the bootstrap button so bootstrap also has a collection of buttons you can use and there you go you have a modal it's that simple understood doesn't do anything and close will close it so since we have two options for buttons which one do you want to use I guess it's up to you but I kind of like the button we already have so what I'm going to do is I'm going to take our button cut it go over to edit employee and replace the button they have there so paste that here and then just change one thing about the button which is the on click Handler so handle show and that is the function that will allow the modal to pop up now we should be able to remove this button now you might notice one has a lowercase and one has an uppercase so that's because this capital B button is a custom bootstrap component we're just going to use the standard HTML button so let's go back to our site and now it looks normal but our update brings up a modal that's all I got in this video in the next video we're going to create a form inside of that modal so if you just want to crank through these videos I recommend going through the playlist link which I'll leave down in the pinned comment that'll make it much easier to follow this series thank you for watching and I'll see you in the next episode [Music] foreign everybody this is kind of part two of creating a modal this video is going to focus on how to create a form that goes inside of that modal and how to style it nicely using Tailwind so be sure to check out the previous video which is how to create a modal and how to make it pop up when you click a button surprisingly simple with react bootstrap we didn't have to do anything from scratch so now let's get into creating that form so I'm going to cheat and actually use code that already exists out there on the Tailwind website which will already be pretty well styled and we can just put it inside of this modal so for form styling I just looked up forms and tail and CSS and found an article to some examples or forms as well as a plugin you can use so let's take a look at this one here this is what we're going to use it gives some pretty good examples however if you want to get really detailed with forms you can check out the forms plugin which will give you uh other capabilities that I'm unfamiliar with so check it out if interested but basically we're going going to go off of this example which I like but we're not going to take everything because we don't need this checkbox probably not going to end up needing this button either so basically we just need the full name and then we need the roll which I don't want it to be a password so we're basically going to go just off of this full name and copy it twice changing it to roll so the first thing we're going to get this surrounding div here and that first input as well we will skip the next div which has the password and then we will skip the next div which is the newsletter check box and then we could take the button just to go through some other examples so let's go ahead and first copy this part at the top and then we'll go here afterwards and copy this at the bottom so going back to our code this is going to go inside of edit employee inside of the modal body so before we go ahead and paste everything let's go ahead and just update some of this information so this will be update employee and this understood will be something like update save that and that should be good now we can go into the body and paste our form gonna need to do a little bit of formatting here so tab this over we'll need to do a few things we'll need to change class to class name and we'll need to add an end slash to the input so let's go back this time we will grab the ending so everything from here to the bottom and we'll paste that after this div and then same thing here we'll just try to clean it up a little bit and it should look something like this great now let's go ahead and fix that error with the input we will put a slash here change the ID to just name for simplicity's sake and that will allow us to change the label as well so instead of associating the label with inline full name we will associate it with just name now we'll save it formats a little bit next thing we want to do is replace class with class name so you can hit this drop down and we want it to be class name like so and you can go through each one of these which will just you can make sure you're doing the right thing or you can just do replace all if you're pretty confident which I didn't want to do that one because it already has class name so we can skip that one all right there we go so at this point everything should have class name which is the right way to do it in react last thing we want to do is we want to take this input for the full name and copy that so we can have an input for the role so that's this div right here so let's go ahead and copy this and paste that right below then we just gotta change a few things so the 4 is going to be roll the text is going to be roll and then the ID to associate the label to is going to be roll all right let's check it out let's make sure we're not totally off when it comes to the styling so we can go in here hit update on any of these and hot dang look at that that looks pretty sexy although it's a little strange we have two buttons here and it has Jane Doe twice so here's what we want to do we need to decide what button we're going to use do you like the button here do you like the button down here well personally I like the button down here it just makes sense but the sign up button is within that form so you're gonna have to do some kind of a rearranging if you want to use this button for this form it's a little harder to submit but I'm going to show you how to do it but in other words this sign up button you can see that it's down here and a button inside of the form will automatically submit the form so there's lots of ways around this I'm going to show you one so basically what we're going to do is we're just going to drop this button all together get rid of that save looks a little bit better now and for this other button well on a typical HTML button there is the form attribute that you can associate a button with a form this button with a capital B versus a lowercase B I'm not entirely sure if the bootstrap button has this ability or not so basically what we're going to do is we're going to say button form and set this equal to the ID of our form so we can scroll up find form give it an ID and we'll just say edit modal scroll back down and assign that here and then we will close the button and then provide the value we want to be displayed here as update so take a look at it now we have this new update button but it looks like trash but you can see that the page is refreshed and that's the easiest way to submit a form with a button so if you guys know how to do the equivalent with the button with a capital B bootstrap button then by all means go for it drop a comment how you do it but for me all I'm gonna do is add some classes into this button to make it look like not a piece of trash so we'll say class name and assign a few Tailwind classes and then we'll just remove this button altogether so what classes are we going to apply we would just copy one of these button examples from the Tailwind docs this one looks fabulous so let's go ahead and copy these classes here paste that right here save let's take a look at what it looks like so we'll hit update and overall not too bad and the button is now associated with that form and we're not using the bootstrap button if you want to keep things consistent here like with the sizing of the buttons we could just do the same exact thing for the other button so I'm gonna go ahead and copy these lines here and this one we're going to change to close get rid of the form button and replace it with on click and this is going to be handle close get rid of this original button save and now you can see we have two buttons and now we can just change the color of the close button so let's go back here you can look up what classes you can use for these so we'll go ahead and just search background on the Tailwind site color and here are some different options so maybe we'll go with like a gray here so we'll go BG slate 400. right here and let's see how that looks yeah it looks a little bit better and we could talk about what color we want it to be on Hover as you can see our coloring is a little bit different throughout our site so you can see that this button is actually using background purple 600 so we could do the same thing for our button over here so background purple 600 and you can just slightly change the color when it's on Hover so purple 700 let's take a look what that looks like so we'll hit update and now we have a purple button it's slightly darker when we hover over it we can do the same thing for close so we'll just put background slate of say 500. save and now it's looking pretty good at this point we are making good progress but if you've been following along you may have noticed there are some errors in the console and the data in the form doesn't actually show the data for the employee it just has a hard-coded value so let's first take a look at that error you can see this error here he provided a value prop to a form field without an on-change Handler this will render a read-only field if the field should be mutable use default change otherwise set either on change or read only so you can see we can't type in this box so what we're going to do in the next video is we're going to talk about what that means how to fix it and how to send data from the actual employee to the form to show the default values there so stay tuned for that video looking forward to it and be sure to subscribe [Music] hey everybody welcome it's Caleb in this video we're going to talk about how we can create an edit form and have the data automatically show up in there as the default value we're going to talk about some of the errors we've been getting in the console this is basically a continuation of the last two episodes so be sure to check those out to get up to speed if you want to follow along using the repo then I just committed added modal and styled form and I will push this to the repo so here is the URL if you want to follow along from this point in time so back to our original problem we have this error or warning I guess you provided a value prop to a form field without an on change Handler and this makes this thing read only and it gives us a suggestion to use default value so if we go back and in our code we find where we have value and we change this to default value now we can go in here and change the data and it works and on refresh we don't get any errors regarding the form input at all so that's good but what exactly is the difference between default value and value well by default it's kind of confusing but by default I would use value then you're just required to provide an on change event handler so what happens when you change the value that's what is essential for the situation basically eventually we're going to tie this value here to our state in our application which is going to come from a specific employee so instead of saying Jane Doe it'll say something like Sal and when we change that data in the form we want to basically update the value being displayed so that is why we need the on change it's to associate the value inside of here with the state of our application which we will update here so that's pretty dang confusing let's just go through an example and try to get our employee data to show up right here basically anytime we're going to do something like that we have to get the value sent from above so we're going to say props dot name and similarly I'm going to get rid of the on change for right now same to down here we're going to replace this value with props dot roll this props variable needs to find and we're going to Define that as a parameter here so we'll say props and then this is going to be passed from the employee file so when we say edit employee we're going to say name is equal to and you can see we already got that value sent from above again so we're just going to basically pass it on down to the edit employee so Props dot name and role is going to be props dot roll so let's go back to our page hit update and look at that it automatically filled it with the name and the role so that is step one the next step is to have the edit modal maintain the state of what is in that form so when we change it we want to store that information in a state variable the end goal is we hit update we grab the most up-to-date value and replace what's on the original page so we want to be able to go in here and change this to some other name and when we hit update it will replace this name here so let's talk about how we can store the data and real quick while I'm at it I'm going to update the width of this thing you know I get these like random fixes I want to do as we're going but yeah let's go on a little side quest see it's looking a little bit better let's just go in here and say Min width is 350 pixels we'll do the same thing for the max width so it's all the same size Max width is 350 pixels I haven't had any issues with different heights but if we had different length of titles you might need to change that as well by sending a minor in Max but yeah that looks a lot better now let's go back to what we were doing which was I totally forget ADHD here my golly alright so we're going to go back to the edit employee and we are going to maintain whatever value is right here inside of a state variable so we'll just copy this line here and we're going to replace it we're going to need two of them actually so let's push that one down and this is going to be the name and then set name the default value is actually going to come from props so props.name same here we're going to say roll set roll and the default is going to come from props.roll so basically we're going to maintain state in this component but we're going to get what it starts with from above and that's what by above I mean from the parent component and that's what's going to show up down here in the value so instead of props.name we're going to replace this with the name variable and same thing for down here we will replace this with the role variable and at this point it should look exactly the same we didn't change any of the functionality and it still works just fine but now we have the ability to put the on change to update that state so let's start with the name we will say on change and what are we going to do here we will just have an arrow function and this is going to invoke set name and pass in what is currently in the text box and the way you do that is with e dot Target dot value where e here this is just a variable name you can name it whatever you want you just have to Define it as a parameter on that function so we'll save that let's check to see if that works here so Caleb Curry close enough and it works so that's one's working but the role is still broken I can't change the value of that so let's go ahead and do the same thing here making sure to update which variable we are updating it's kind of a confusing way of saying that but you guys get what I'm saying so on change and then we will change this to set roll now we should be able to update both of these depending on which one we want so obviously that's a lie so we'll just say uh Dev so at this point we basically create a variable a state variable we load the default value from the properties that are passed down to the edit employee component and as we change that form we keep track of what the most recent change is the final step is on update take that most recent change or whatever's in that state variable and apply it to the original page which is exactly what we're going to be talking about in the next video the way we do it is a little bit strange but once we go through that video it should make some sense so stay tuned for the next episode I'll see you there [Music] all right we are finally here the video where we finish up our modal it only took us what like 10 episodes 11 episodes into this series and the last four including this one have been dedicated to creating a modal so go check those out if you want to know the basics but here's where we're at by the end of this video we're going to update the data showing up on the main page so we got this sick modal here it's crazy how cool it is but it doesn't change what's over here so if I hit update well currently it does nothing it actually refreshes the page we got this question mark here none of the data actually changes so for a single page application we want to avoid any page refreshes whenever we can and we want the data to be updated dynamically when it's changed in state so right now we pretty much have two pieces of State the first piece of state is this state right here which is a temporary holder for what is typed in into these boxes here the other piece of State actually comes from Aptoide JS this data right here which is all in state so how do we update this data from this data and the way you do it well you got to think of how is our structure currently well we have our top component which is app.js this has a component in it which is the employee and then inside of the employee we have the edit modal which includes the button and the modal itself so a friendly reminder first that props are not meant to be changed by the components even in the modal component we created state to be able to change it we had to create that extra State variable so if we wanted to change the state from a parent we actually need to pass down a function a callback function that will be executed when we want to which can then change the state in the original component all right so here's what we're going to do we're going to head over to app.js and we're going to create a function we can just Define that that here we'll say function update employee now we're going to need a way to identify which employee to update we're going to use an ID for that and then we're also going to need the new data that we're going to replace the old data with so you could do that as an object or just as separate values since we're only having basically two values name and Rule it's really not that complicated just to have separate parameters here so we'll say new name new role and we'll just for now say console log update employee inside of app.js so we can see if we're actually getting this function to execute now what we do is we go down to where we have our employee and we're going to include another prop here update employee is going to be equal to update employee so you don't have to do anything fancy with the naming just keep everything consistent then we'll go into employee we're going to do the same exact thing passing it down to edit employee so we'll say update employee but this time we have to say props dot edit employee because it's a property now so we'll save did a little bit of reformatting for us and then lastly we'll go down to edit employee and it should be available to us so what we'll do is on click of that final button scrolling down finding that this update we can say on click and actually now that I think about it this is one way of doing it if you just wanted the button to submit the data versus using the form but there's a better option since we're within a form we can scroll up and at the start of the form we could say on submit and this is going to be a function and it's going to invoke update employee the form data is available to us we can access it through a variable on the parameter here we'll just call it e and there's a few things we're going to need to do here as well the first one is e dot prevent default and that is how you prevent a page refresh additionally I'm going to do a console log just so we can see the function be invoked here and say hello from edit employee and let's go ahead and console log all the data that we need for the function so the ID and the name and the role and I know we haven't defined the ID yet don't worry about that we're going to do that here soon and we'll just need to pass all that information to the update employee so all we need to do now is add an ID to our employees so we can easily identify them this will be from app.js I don't even use this title and file or this index.js I'm just going to get rid of this so let's go ahead and add an ID to each one of these doesn't really matter we'll just go with numbers and increment pretty standard surrogate key here and there we go now I don't know if you guys remember when I introduced the idea of using an ID there and that was when we were using this key here so since we have a unique ID for each one of these you no longer need to use a grid so you could just say employee dot ID and we're not going to console log the grid either this ID will need pass down as well so I'm going to actually put that after the key so we'll say ID is equal to employee dot ID same thing it's going to have to be passed down from employee so where we have an edit employee we'll say ID is props dot ID lastly we should now have access to it here but it's going to actually be props.id so why is this one props ID and the others are not props ID well that's because this name is referring to this state variable here as well for the role variable where we haven't created a state variable for the ID we actually don't really need a state variable because we're not updating that value at all so we'll just stick with props.id here all right so that was a lot of changes hopefully something works let's go to our page we have one issue update employee is not defined on edit employee line 38. this is going to be props dot update employee because it comes from props now our page is working we can go in here and we should be able to change some of this data let's open up the console and we'll clear that out let's just change her name to something I don't know something more common we'll hit update we get some errors I think this just comes down to a typo because I accidentally used edit employee so we need to pass down update employee yeah not too bad I only had like one issue hopefully that'll work we'll hit update let's see what we get and it says hello from the edit employee we got the id2 the name salamander and the manager Rule and it goes all the way up to app.js where it gets those values so far what we have is a success the first time doing this it's a little confusing like so many different layers but we still have one more thing to do we have to take the data that has reached app.js and we need to update its state so heading back over to app.js let's find the update employee function which we defined right here and let's figure out what we need to do to change the state well the first thing we need to figure out what one of these elements we need to change so you can Loop through check for their ID and if you find it you can replace the name and the role and eventually you can do the image as well but right now we're just working with the text so let's go ahead and create a variable updated employees and we're going to use map to our advantage and then at the end of this after we've updated our list I'll show you what to put in here in a second I just want to not forget the main thing which is to actually change the state so we'll say set employees and pass in updated employees so pretty much this whole function is just to create a new list and replace the state list so inside a map this is going to take a function so parentheses Arrow curly braces inside the parentheses each iteration it's going to be assigned to this variable so we'll call it the singular version employee and all we're going to do is just check for the ID being employee.id if that's the case then we will return the new employee otherwise we will just return the employee as is so we can create a new object using this fancy syntax here so we're just going to say return dot dot employee which will expand out any of the attributes of employee and put it in this curly braces which is the new object so this is called spreading if you want to learn more about that and then we're just going to set the name to new name and the role to new role this will do the trick so let's save and let's go try it out so let's go in here and we'll update one of these update close out of it and you can see the data changed fabulous we did it so just to go over the syntax one more time if you were basically trying to visualize a different way of doing this instead of using this spread thing you can basically just replace all of the elements so you could say image is New Image and that would replace all of them the only thing is you will need to get the new image as a parameter or if you just wanted to force it to stay the same you could just do that this should work as well so let's try it image is not defined so let's just say employee dot image there we go let's try it again let's do a refresh obviously this data is not stored in a database anywhere so it's not going to stay after refreshing so we'll change this to Johnny and updates works fine let's change their role so his name is his role as well now so everything appears to be working oh I just thought of a problem though because if you see right here down here it says undefined we basically nuked the ID when we got rid of that spread so you got to be careful that you make sure you grab all of the elements which the easiest way to do that is to not do it manually and just have it do it automatically so we'll just do that and then just replace name and roll that's the smarter way of doing it I was trying to be handy and show a different way but you'll need to make sure you have the ID and the image in any other attributes you end up adding if you don't want to replace them so let's try this again and make sure we don't get an undefined so let's do a refresh so we'll just repeat that so update Johnny update all right it has a three why is it not closing I think we need to add into here handle close let's try that hit update there it closes okay that should be everything so now we should be able to change the data it'll close and update now you can go back through remove any of your console logs if they were coming in handy we don't need them anymore but sometimes it's nice to do that so we'll go back to app and remove the console login here as well so thank you for sticking with the series so far getting through the last four episodes on the modal hopefully this is a pretty good intro on working with lists inside of state and how to pass functions down how to maintain temporary state that we can then pass back up through that callback function all that stuff I really appreciate it hopefully you're learning and coming up with some cool use cases and examples at this point you can probably start you know working on some of your own stuff pulling these principles into it and hopefully building something cool we still need to learn how to extend the list add to it so maybe having an add button that could add new employees we might look at that next guess we'll just have to see for the next video thank you for watching stay tuned peace out and be sure to subscribe foreign [Music] how to add to our list in react so we have a bunch of employees how can we make a new employee show up in that list and I know what you're probably thinking did I Slob on myself yeah okay I did all right drinking is a hard task and you're just gonna have to deal with that okay nobody's perfect like you so let's just get started okay as for a quick preview of what you might expect from this app first off we're going to need an image URL we can go in and add an employee give them a name some role I don't know bank teller sure paste a URL hit add and they instantly show up on the page and of course you can go in here and change this give them a new name update and it shows up on the page so we built the edit capability in the previous episode so be sure to check those out if you're interested and if you want to jump in right where we're at to add this new employee button you don't have to go through the whole series if you don't want because you can just check out a certain commit in the repo so we are at Finish edit modal and here is the URL if you want to access that it's a little tiny so I'm going to go ahead and zoom in a bit for you guys in this episode and where do we even get started well first off let's just clean up a little bit we're not going to need the employee component for this video yeah we're still going to use it as is but we're not going to modify it because when we add an employee it's not associated with any individual employee so that add button is not going to go inside of the employee component this is a bit different than these buttons which are in every single one of these employee components so what we're going to do is we're going to close out of employee for right now and inside of our components we're going to create a new file and this is going to be quite similar to edit employee so what I'm going to do is I'm just going to click edit complete and copy paste and then what we're going to do is we're just going to rename this to add employee and we'll just go in here and change some of the code so obviously first this is going to be called ad employee and that's going to change the export at the bottom as well add employee great now the main difference here is that with the edit component the values for the employee are pre-filled the ad employee is not going to have any default values you saw in the example there was like a grayed out text is to show as an example which I'll show you how to do that but we're not going to preload any data this means that these values here props.name we're not going to want to use those and instead we'll just go with an empty string and you'll probably want to use an empty string versus nothing if you want after this video you can try changing that and you'll see a warning in the console explaining why all right now let's change the text of the button and put it on app.js we're not going to need any other files I don't think for now so we'll just go ahead and shut that and we're going to change this to plus add employee now that we have this button here let's figure out where to put this inside of app.js we want it to be after all of the employees so you can see this div here surrounds all the employees so we could put it right here and we will just say add employee and close it like so that also imported so you'll want to make sure you have that at the top from components slash ad employee all right so that should be somewhat right let's scroll back to the site and see what we got we have this add employee button over here it does pop up a modal it's just not exactly what we want maybe we want it to be centered and I actually prefer the look and feel of these buttons versus these rounded ones down here so what I'm going to do is I'm just going to copy the styling for those buttons which should be down at the bottom here so we have button with these class names so we'll just take this I'm actually going to take this one because I want the purple color but you could change to whatever color you wish and these are the classes we're going to use for our button at the top so let's find that and we will just replace all of these classes here yikes that's a lot all right we'll paste that there and save take a look at it and there we go we have the add employee here now we just have to figure out how to center it what we can do is say MX Dash Auto so margin on the x-axis to be automatic and I think for this we will need to make this block save there we go if you want to be a bit more spaced out you can add margin so n two and that'll push it down just a little bit all right so far it's looking pretty good we just want to change some of this text so instead of update employee it says add employee so let's go into ad employee we'll search for update and replace that with ADD and we'll have to deal with the function later when we deal with the functionality for now let's just update the text on the modal take a look and there we go next up we're going to add the image input so we'll go back find the input up here that we can just copy as an example so I'm going to take the label and the input so this entire div right here will include both of those so I'm going to copy that and we're just going to go down to the next line and paste it change the value to image the label and then what we can do is change the 4 to IMG and change the ID to match that IMG so this is what it's going to look like right here and just to be very specific we want to say image URL we're not dealing with image uploads right now so we'll just want to make sure we take a URL now as we're getting an example value here for people to see that's called a placeholder so you can go in here and add a placeholder and put some URL or you know you could make it more specific to an image URL this will do for me and then I'm going to do the same thing for the other two inputs so we'll add one here we'll say bank teller and we'll add one right here there we go so we added values and those should show up in a light gray here taking a look at the padding if you go into the classes there's a padding X4 if we change this to a three we can take a look how that makes a difference we'll scoot the name over just a little bit which I just think it looks a little better this seems oddly padded so you can adjust how you wish I'm going to go with three but yeah just some practice getting some changes into the classes and getting familiar with the padding so we'll change all of these to three take a quick look how that looks overall not too bad now we just have to figure out how to actually make this show up in the employee list so similar to how and we had the edit employee we took a function from app.js and we passed that down through the components we're going to do the same thing but this time we don't have to go through the employee component we just go direct so let's define a function up in app.js and pass that as a property so here I am over an app.js we're going to define a new function new employee most likely you're not going to need to pass in an ID as the employee doesn't already exist so we can just generate one but we are going to need the name the role and the image and now inside of here we have to set our employees list and inside of here we want to basically take the existing employees plus an additional employee so the way you do that is you make an array and then you say dot dot dot employees so that'll take each employee and put it in that list and then we just need to add a new element to the array here so we'll say new employee where does this new employee come from or actually going to create that right here so new employee is equal to something if you want to take a second and guess go ahead but I'm going to type it out now it's going to be an object with the ID the name the role and the image basically we just have to copy this structure up here defining a new one down here so the ID well these ones are just hard-coded values imagine these are coming from a database so if we're creating a new employee you would probably rely on the database to do that for now we're just going to use the uuid V4 that we used in an earlier episode so again for this you're going to need to import this here making sure to npm install uuid so this is going to generate a random string of characters and that'll do now for now for the ID the name that's going to come from the name parameter same thing for the rest of these here and it is smart enough to know that this is the property on this new object and this is the parameter you can see the highlighting there now this function is defined in app.js but it's not being used anywhere so what we need to do is when we have the add employee button we need to pass it as a prop so we'll say new employee is equal to new employee the function here and we're not invoking it just as a reminder we're just putting the name of the function now that should be available inside of AD employee so on form submission scroll up to where the form is submitted on submit first thing this handle close we we dealt with that in the last video so I was thinking about this you could actually if you wanted to get that out of the on submit it doesn't matter it's probably fine if it's there but we could just take this down to the button and I think this was how it was originally set up I just changed it at some point so we'll just clean this up move it down to the button down here and we just want the name of the function so there we go handle close all right now we're back at the form submission so e dot prevent default to prevent a refresh and then props get rid of update and replace it with new employee passing in name role and image now for image I'm going to keep track of that value the same way we're doing it up here so I'm just going to copy this paste it and replace this with image and set image this is going to be tied to the image input down below which I don't think I ever updated what the value was pointing to so this third one here we need to replace it with image changing the set to set image okay I think that might be everything but there's like a 95 chance I screwed something up so let's try it again new employee is not defined on line 60 alrighty let's go back and take a look we just need to say const and then on 95 as well so let's take a look there 95 the function name is not being recognized I just need to lowercase this in there we go okay now the page should be working let's try to see if the functionality is there John Smith Bank guy and for the image URL you can actually close out of this and copy an image address and when you add employee all that data is going to stay there paste add and it shows up that took quite a bit of jumping around and we're not actually quite done but so far it's looking pretty good you see here's a problem if we go to add a new employee uh-oh all that data is still there so we don't want to be able to just do this we want this to refresh every time we add an employee so that we're not just adding the same thing each time and we also don't have to go in here and delete the old values so all we have to do is reset the state when we click the add button if you want to try and do that go ahead and give it a shot what you're going to do is you're going to go into add employee and each one of these States can be reset on form submission or on the add button click I'm going to do it in the form submission since we've already been working with that so right here we can just say after the E dot prevent default set name to empty string Set Roll to an empty string and set image to an empty string there we go now let's give it a try we'll add one of them here and then let's click add employee again and you can see the information has been removed so that was quite a long video but hopefully you got it all figured out if not feel free to re-watch it and stay tuned for the next episode I think we're going to be doing something new that's going to be really cool we're going to learn some more concepts of react Peace Out And subscribe [Music] foreign ful people in this episode we are going to be refactoring our code to talk about a new approach of passing data from a parent component down to a child component so you're what 14 episodes into this series you're probably wondering how could we build anything better than we've already built well by the end of this video we're actually going to have the exact same thing what what are you talking about Caleb why would we do that well because we want to talk about a new approach and we want to build the same application using this new approach it's nothing major the main change we're going to have is instead of passing data down multiple layers we're actually going to pass components down so for our example we only have three components that are chained we have app.js employee.js and then editemployee.js and we have a function that we're passing down all the way down to the edit employee well that's three layers you might be working in a more complex application that's several layers nested and in that situation you're never going to know where things are coming from and you're just going to be confused so in that situation you might want to try this new approach which is to actually pass a component down as a property so might be confusing you might be like what are we talking about but let's just jump into the code and try to make it happen and get the same exact result on the application so this is what we currently have and we have the ability to update an employee type in new information and hit update the way this works is if we go back to our code inside of app.js we are passing this update employee scrolling up you can see this is a function which extends our hard-coded list right now eventually we're wanting to work with permanent data but for now we're just trying to get used to the front end stuff so this is passed to the update employee prop inside of employee it's passed again down to the edit employee component so what we want to do instead is we want to define the edit employee component inside of app.js and pass that to the employee we want to do that for every single employee so we're going to do it right here so we'll just say something like const edit employee and this is actually going to be set to 2 an instance of that component so it's going to look like edit employee now you can use where we invoked edit employee earlier as a template on what data needs passed so we need the ID the name the role and then the function so let's go ahead and actually just copy this edit employee because it's going to be pretty similar and we'll go and replace that eventually so we'll go in here and we'll paste that right here save and this is our new edit employee the difference here is we're no longer going to be invoking update employee from props because this is defined directly in the same file which is right here all right so we have a component what we can do now is instead of passing this function through the employee down to the edit employee we can just pass the edit employee as an entire component so we will change update employee to edit employee and change this to edit employee as well so now what's being passed is this variable here which is a component you may think that the syntax or the way of doing this is a little strange but if you remember when I introduced jsx they gave an example of this as well where they actually assigned well it looks like HTML to a variable they can then use that variable anytime they want to refer to this H1 we're doing the same thing we're just using a custom component called edit employee and now that we're passing this component edit employee all we have to do is go into employee and we're going to replace this section of code what we want to do is we want to refer to props dot edit employee hitting save checking out our code we'll go back to react app we have a problem edit employees not defined must have typed it out wrong so I think this is actually lowercase e dude I screwed up big time wow all right so what else I think this needs imported so let's scroll up to the top and it's going to be pretty similar to the ad employee it'll just be edit employee from components edit employee this other issue regarding props this was originally defined in employee so that's why we have props here we have to replace this with the instance of the employee we're talking about which is defined as this parameter here so we're going to say employee dot ID employee dot name and employee.roll at this point I believe everything is working the first iteration just as an example will grab that first employee it'll grab the ID the name the role and it'll grab that update employee function it's going to make that component and then that's the component going to be passed to that edit employee save check out the site we should be able to go in here let's do a quick refresh just to get a clean State and and just put something in there it doesn't really matter you can see it works exactly the same way that's pretty much it pretty simple change but this concept can be expanded so if you design a component where you expect people to just pass in some section of code this is how you could design that you know if I designed a web application to let's say split the panels left and right you could just take a component for what's displayed on the left and a component for what's displayed on the right and you would expect a component to be passed in and you could design the structure component to be very general that's all I have in this video hopefully it gave you a new way of thinking about things in the upcoming video I'm going to be trying to place a banner up here at the top because I want to get onto navigation so the ability to switch pages and to talk a little bit about how you can build a template for your application so that's our goal over the next couple of episodes so definitely stay tuned tuned for the next one [Music] what's up everyone welcome back to your react but actually we're not doing react really that much in this video because we're actually going to be doing more design stuff but it's going to be a little bit react because we're putting it inside of a react application episode 15. so let's get started what we're going to be doing is we're going to be creating a banner on this site and this is going to be our navigation that will yeah I guess Banner isn't quite the right word because Banner is usually like a temporary thing like oh we just released version two or something so I think navigation would probably be the better choice of words and we have been using Tailwind CSS so far for the series so as always we're going to use some of the existing code for tailwind and modify it to fit our needs so if you search tailwind and then navbar you'll find something from not go away Tailwind UI Ai and Tailwind UI is a paid thing so basically you can pay to get some like pre-built components that you know work really well and just to show you the difference we're also going to look at banners versus nav bars so go ahead and go to the tailwindui.com site We're not gonna have to pay anything for this video because there's a another thing you should know so we're going to look at banners you can see these are banners here not exactly what we're looking for we're looking more for nav bars so if you go through here you can find what you like for example I really like this one down here at the bottom pretty simple but when you click get the code it costs money so we're going to talk about how we can pirate this now I'm just playing no pirating because the first one on here is free so if you go up here you can go to the code and look at that it gives us everything we need to create this navbar another thing there's this drop down here and what would you look at that they make it react friendly so now you don't have to go through here and change class to class name in 300 locations so here's what we're going to do we're going to copy this component you can see it's just example so you can go in here and change the name but there's a nice copy button right here and don't hesitate to consider purchasing if you want to you know try out any other other examples now I don't have an affiliate code I'm not sponsored or anything so just mentioning that but you can Tailwind if you want to sponsor me hit me up all right enough messing around let's get back to the code so let's go over to our application I'm going to commit our previous changes just to get everybody on the same page so I just called this pass component if you want to jump to our location and inside of our source code we're going to go into components new file I'm just going to call this header.js paste their code I'm going to scroll up and this actually has the export with the function definition which you can do so we don't have to have that export line at the bottom I'm going to change the name of this to header save did some reformatting for us and then let's talk about how we can bring this into app.js so we'll go into app.js go to the very top of our code so where it says return inside of this div here we can put the header component save we will need to import this so import header from components header alright let's take a look at our site and you can see it needs a few modules to be installed with npm so it looks like headless UI for react and hero icons for react so we're going to copy this and we're going to say npm install paste that and then we'll do it again with hero icons all right those should be installed they were added to our package.json and now we should be able to go to our site there we go now I like this one pretty well but if you're not sure there's another page where you can get some examples which is under headers and the Tailwind UI site so this one will allow for drop downs which is pretty nice if you have a lot of pages to organize and they do have a free one here that you can use I tried this out on another application and it worked fairly well so here's my example that I was just playing with earlier obviously it's not the most beautiful thing ever but I got rid of the drop downs and just created these without the underline but I decided that the nav bar just looked a little bit better for what I was trying to do sorry my computer is kind of slow I'm running everything on a little MacBook Air so that's one thing I want to get rid of these underlines I'm not a fan of those so let's go over and figure out how to do that so we'll go into our component that we just created header.js scrolling through here we want to find the a text so if it's a really long component you can just search for the text so we're looking for dashboard or like team or project or something so dashboard oh interesting it looks like they have it defined in an array here it looks like that array is mapped through down here on line 58 so let's go ahead and try to add no underline and we will also add it here as well no underline so save let's check out the site see if it worked and you can see the underlines go away now we just need to change a few other things you know we need to figure out how to get rid of this old guy maybe change the logo and so forth let's take a look at this image here so we can find that over in the code as an SVG file right here so this is the first URL we can command click or control click this is the first one and then we also have this one as well so that actually appears it's just the same logo just for different screen sizes and then there is a third image down here as well oh it's the old guy anyways I'm going to get rid of this image for now as well as these two images you could of course replace them with your own images if you want to go design a logo we actually just get rid of this section all together let's go back to our app see how it looks and to me that actually looks a lot what oh that's an input I put earlier so we can go delete that let's get rid of this here all right there's our application a slight change I want to make to this is shrinking the height of this bar and you can do that with this h16 here defined in the header so this is the height so we'll go ahead and change this to something a little bit smaller such as 14 and you can see it shrink just a tiny bit and then if you wanted to change the background color of your whole application maybe to fit with this a little bit better or you know if later on we want to do a light mode dark mode kind of thing you can go inside of app in here we can define a background gray let's say 300 which will just give us a light gray background and it doesn't fill up the whole page so we basically need to tell it to set the minimum height of the app to the full screen so the way you do that is with Min height screen saving this you can see it fills up the entire screen like I said this course isn't about design so yeah it might not be the most beautiful thing on planet Earth but it at least makes working and react a little bit funner instead of just staring at text on a white background last thing we will want to check is if it works on mobile so the way you can do that is by opening the developer tools and then going to this button right here that'll put it on a mobile device and took a second to kind of refresh but this is what it'll look like and then you have this button here which will drop down these different pages so if you want you can add a little bit of margin might make it look a little bit better inside of app we can scroll down to where we are rendering the components and inside of here we can just say margin Y 2 and there we go it scooted it down just a little bit let's turn off the mobile preview and see what it looks like and it looks pretty good you might want to change the style a little bit you know maybe make these buttons gray or change this top bar to some shade of purple whatever you might want to do go for it at this point we have the nav bar but functionality is not there the links don't work and we don't really have logic to decide which page is the selected page so that's what we're going to be talking about in the upcoming videos as well as how to do routing so how do we work with different URL paths inside of react so stay tuned foreign [Music] what's going on everybody in this video and the upcoming episodes we have a few goals in mind so the first goal in this video is to deal with Pages what is a page in react and how is it different than a normal component that's what we're going to be talking about right now the next goal is how we can do navigation and routing inside of react this is directly related to Pages because essentially we want to have an application that has multiple different pages and these are directly tied to different URL paths after we talk about those two things we'll have the functionality to switch Pages by typing in the URL bar but what we want to do is we want to tie that with our nav bar at the top of our website so that we can click through the different pages and have an active link that looks a little bit different than the rest so right now we have this navbar but these links don't actually go anywhere and this active one is really just hard-coded it's not really the active page so we want to be able to switch pages and that highlighting switches to the page that we currently have selected so let's get started with this video now and make sure you watch the next two because they are a group that you should watch together speaking of groups that's really what a page is inside of react so if you look at what we have here now we have these different components we have this ad employee button and these are all logically related so we can think of this as an employees page so I want to extract all these components and put them in their own file that way we're not just polluting this app.js file it works for now but if we wanted to add more to our site it's going to get really ugly additionally if you look through here we have this header right here on line 74. well the header in reality should surround the entire web page that's because we want to have a consistent theme across all pages so we're going to talk about how to do that in this video as well so let's go ahead and create our first page by going to Source create a new folder pages and then right click here new file employees dot JS now since most of this code is going to come from app.js I really think it'll be easier just to copy this entire file paste it in here and then edit some of the content so first off this is going to be function employees and this will change the export at the bottom so employees we can clean some of this old code up that we're not using and likely we will need to update some imports so this is now going to be a folder up and then these will be changed over to a directory up slash components slash employee same here there we go now let's go ahead and go back into app.js and we're going to replace most of this code with just an invocation to the employees.js component so we can get rid of all this state here we can get rid of these functions and we can get rid of everything inside of the return and then all I want to return is a call to employees and that's going to be imported like so now when we take a look at our website it looks exactly the same but now our code is a little bit more organized and we have this employees page it's as simple as that that's how you create a page now I want to show you how you can surround your pages with a header instead of kind of having the header embedded in each page because when we have say five pages we don't want to have to do that for every single one we just want it to be automatic so what we'll do is we will go into the employees we will find where we have the call to the header which is right here and we're going to remove that this is actually going to go back in app.js and inside of this return here's what we're going to do we're going to surround employees with the header so don't close it here instead we're going to have a closing tag after employees so it'll look like this so now you can think of header as wrapping the employees component right now it's not going to work we just see that header but I'm going to show you how to fix that in just a minute but you can imagine having other tabs in here you know maybe we have a tab for file management and you know maybe we have a tab for discussion and now we have this header surrounding everything so we don't have to go put it in each one of these components now this is not the exact syntax you're going to use just kind of using it as an example we'll figure that out in the next episode it will be pretty similar though so what we need to do is inside of header we need to say props here and anything that is inside of these open close tags is going to be added to props in a property called children so what we can do is we can scroll to the very bottom right before this fragment and we can say we want to render all of the children that are inside of the header so to do that you say props dot children inside of curly braces and you can imagine this being inserted into this location it's going to do that for us automatically what that means is our website should now have the employees page showing functionality wise our website looks exactly the same it does this exact same thing but structurally in our code it's a lot better because inside of app.js we now only have like four lines of code here five lines of code inside of the app function everything related to our employees is brought to its own file so we don't have to mix it in with a bunch of other junk and our header is now completely separate from our employees component and it works automatically by surrounding the component the employees page so make sure you understand each one of those things in the next video we're going to talk about adding pages and how to make URLs associated with different pages that all has to do with routing which is a really big part of react so I encourage you to check that video out and I'll see you in the next one peace out foreign this episode we are going to talk about routing inside of react so we want different URL paths to go to different pages in our application so for this we're going to use a tool react router Dom which we're going to install which by the way if you want to follow along exactly what the code we have here we're on the commit introduce pages and children props and you can find the url right here with that we're going to say npm install react router Dom and this is going to have three things that we want to import into our application so it's going to look like this import from react router Dom and the three things we need are browser router routes and Route so let's go ahead and space after the header here and this is where we're going to say browser router and this is going to surround all of our routes so we'll take this and actually we're just going to get rid of the employees page for right now we'll put that back in here soon so it's going to look like this now inside of here we have another definition which is routes and then finally inside of routes we can define a single route and it's going to have two attributes path and then the next one is going to be element and this will be self-closing so this is the structure when you want to create a URL path the path in here we're just going to put a forward slash right now and the element that we want to render this is where we're going to put that component so actually instead of the single quotes I'm going to use curly braces and inside of here I'm going to render our employees page so it'll look like this and save let's see if we have any problems at all on our site at this point we should be able to visit localhost 3000 and get our employees page we can change the path if we want so for example if we said forward slash employees now the home page is blank which you could set up a home page as well and you would need to visit employees and there you go our page is rendered so now it's pretty much as simple as taking the different URLs you want and making those the destinations for these different links in your nav bar and setting up a page inside of react for each one of those pages that you want to link to just as an example and we're not going to build upon this very far we're just going to show how this might work to visit a separate page we could say something like customers.js JK not really j s and then we'll just say export default function customers return each one hello there all right so we have our customers component or you can think of it as a page pretty much the same thing and we're going to import customers from dot slash pages customers and then we will create a new route inside of our routes and this one is going to be forward slash customers and the element we're going to render is customers now on our website we can visit forward slash customers to get that new page and it looks awful but you can see the text there so the next logical step is to work on the header and update those links so you can go into header.js find the anchor tags and update the href which looks like it's coming from the array of navigation points up here so you can change these URLs to point where you want to go we can make the first one to be slash employees and the next one to be slash customers and we'll update the text as well so employees and customers now we should be able to navigate between the two here are the customers and here are the employees and it's pretty much as simple as that but there is a couple of pointers I want to give in the next video when it comes to navigation because right now we're just using plain anchor tags I want to use a different type of tag that's going to be a bit better which will also give us a good strategy for creating the active link so this background will switch over to this URL when we click it so that's we're going to talk about in the next video so quick review we created a header which surrounds all of our content right now it's just a header but you could just the same go into the header file and after props.children put a footer right here so this is going to show up after the content let's go back to the employees it's a little easier to see scrolling down and there is our footer which you know might need some styling of course but that surrounds all of our stuff then we also surround all of our stuff with this browser router which has two individual routes inside of the single routes tag each pointing to a different component which we've mentally defined as pages but really there's nothing differentiating a normal component from a page component they're both defined exactly the same way it just so happens that it logically makes sense to have one defined for different URL paths stay tuned for the next episode where we continue our discussion on improving our navigation see you then foreign [Music] welcome to episode 3 of our little mini series on navigation inside of our larger react Series so the previous two videos we set up routing so our navigation bar works we can click on these different pages but there's a few problems the first one being that the background does not switch over to the active page and that's what we're going to fix in this video and the second problem which really isn't that big of a deal it works is that we're using an anchor tag and there are better react components that we can use for links so we're going to replace that in this video now there is some kind of system here for defining which link is active and it comes from this value here current being true I'm not really sure how they intend for you to use this maybe keeping track of some State on your own but I'm actually not going to worry about it because the way we're going to do it is actually in my opinion a little bit better so what we can do is we can remove all this junk if you've been following along or if you're just jumping in this video from a YouTube search or Google search well then you might not even have that and you won't need to worry about it you just have to keep your links and we're going to show you how to update them this one's doing it in a loop but if you're just hard coding each link out you'll just need to make the change across all of them so the first change I want to do is change this anchor tag from an anchor tag to a nav link and this actually has the active capability built into it so this is going to come from react router Dom which we've used in the previous episode so we'll say import nav link from react router Dom now before we delete this there's a good chance we'll need some of these classes later so for now let's just leave that there and we'll create a new one class name here and this is going to have some of our own functionality and this is actually going to be an arrow function now nav link is going to pass in the active link for us automatically so we'll say is active and it actually passes an object so we want to destructure this object which is going to get us the attribute on that object called is active and that is the value we want so a little confusing but that is the syntax you're going to need curly braces and then parentheses around the curly braces this is going to be true or false if it's the active URL so inside of here we should be able to say console log and let's go ahead and say the href of the item so item dot href plus a space plus is active so this will give us an idea of what we're working with and the nav link is actually going to use the to prop to contain the URL the link should point to so make sure you update that or you'll get an error in the console and now let's just take a look at the URLs and what we should expect so we have slash employees slash customers and these are pound signs which will just refer to the same page so we'll get multiple trues at once so let's just change this to something other and then slash other two just as an example so we'll save that now let's take a look back down at our code the other thing is we're not going to need this line here so we will delete that it's white and this actually is important because you might see this when you're doing this so if you see something like use location may be used only in the context of a router this means that you're not currently within a router or browser router so you need to make sure you have this and you might be like what we do have it why isn't it working well our header is defined outside of that browser router which was probably just a structural mistake on my part so we'll just switch those so that the header is on the inside save it and we should be good to go at this point our site shows up and we have the different links they just don't look very nice so you can click one of these and you can see information popping up in the console if you want a fresh start you can do a refresh and take a look at these white ones here employees true and then all the other links are false customers is false other is false and other two is false so you have that functionality there to check if this is true and if it is style it a bit differently if it's false style it some other way so now this is where our other classes come in so we can go back to the header we can use some of these so the way this turn area is structured these are shared classes so what we can do is apply them here and paste this here we'll say return put this in a string and then we will just say plus and now we can do a ternary to see which one of these we want to grab based on the value of is active so the way we're going to do that is actually with parentheses not curly braces because we're already within a code block and we can say is active if it is active then we will grab this one and the no underline is actually on both of them so I'm going to add those to both no underline with a space because we're doing some concatenation here so I'll paste this value here otherwise I'll paste this value here all right so we'll save that take a look ah it's working except we got it backwards so I wasn't sure which one was which let's just switch this is active or you could switch down around the classes either one would work fine so right now only the active one is going to have that background and if we switch to customers you can see it maintains that background so just a quick review we use a nav link we use a 2 to point to the URL then we returned a list of classes and we were able to condition on the is active variable which we got right here as a parameter destructured with the curly braces you can look into that if you want to know more concatenated with stuff that should be displayed if is active is currently false because we inverted it and then if it's true and there you go that is how you maintain which URLs are active and you don't have to do anything with managing state or really anything too complicated it's all built in with that nav link so that's what I recommend using and then throughout your pages you will want to use the link component whenever you have a link instead of a plain anchor tag we might get into that later but so far we haven't had any direct links in our page but you can do some extra research on that if you're interested or you can just continue on with the series with the next video reminder playlist link down below and I appreciate you sticking through it these last few videos on the navbar were a little bit complicated lots of rearranging might have been difficult to just jump in if you just found this video on the internet but for those of you who have gone through it really appreciate it and definitely would appreciate a subscribe thank you I'll see you in the next one foreign [Music] hey buddy hey everybody Welcome in this episode we are going to be going through what we've built in our application so far doing some cleanup especially around the header because in the next section of videos we're going to be doing something new and we just want to make sure that we kind of close off this section with some cleanup the next application we're going to build is actually just going to be on another tab on the same website so we're going to have everything inside of the same page but in order to do that properly we want to make sure our header is set up nice and clean which going off of some of the things we did in the previous video it's okay but there's actually some changes some things I could have done better so if you're just jumping into this video and you haven't watched the rest of the series then a lot of this probably is not relevant so you might just want to start with the next video but if you've been following along definitely watch this video and make these changes so let's first take a look at where we're at here is our site there's nothing on the home page right now we have the employees section and then we have this customer's page as well which currently just says hello there and this is what we are building in the previous video talking about the navigation these links don't do anything and that's fine just showing how to do it but first off this isn't actually correct we don't want it to be in this blue color and I think it's just because I incorrectly put it as part of the header so we're going to fix that first so that every single page is going to start first thing right after the header with the appropriate amount of space so that's what we're going to set up first additionally we never took a look at mobile so if you go into inspect switch over to mobile it looks pretty good but still a little bit of short spacing here and when you hit this our links don't look the same as when we're not on mobile you can see they don't have the underline and they have a little bit of highlighting so we're going to apply those Styles as well so let's jump over to the header file and you'll see this is where we defined our styling before we used a nav link and a class name and the way this is going to be set up is I'm sure dependent on what header you end up using or if you write your own but in the case of this header that we took from Tailwind css's site there's actually another section if you scroll through here with some more class names and then scrolling even more there's a another section with some class names so what are all these things pointing to well this first section up here is actually referring to the section that had an image of your user signed in this profile drop down which we have since removed from the page but I don't know if you guys remember there was a little face here showing that someone may have been logged in and you could click that and then it would show some menu options since that's not showing up this code isn't really hurting anything and you know you might want to add that in later however we do have access to Source control so if we needed to go back and get this code if we deleted it we could easily do that so what I'm going to do is I'm going to take everything in this menu and you can close it with this button here and I'm going to delete it so from line 85 to 152 in my case save and now our site looks pretty much the same but we really shortened our code and now we just have two sections with classes so that section and then the one we created earlier for the main header links so these are the header links on desktop and then these are the header links on mobile so what I want to do is I want to just copy this setup here so we'll copy the nav link right there and we're going to paste this down here and use it as an example so we can switch this from a disclosure button to a nav link so right inside of the loop we'll paste that here and then obviously do the necessary formatting and we're going to have the key is item.name and then we're also going to the class name but we're going to use the is active property to conditionally apply the classes so let's go ahead and copy these classes and we will replace the ones we have here keeping the no underline because we want to add that one in and the other two are exactly the same so let's go ahead and remove this disclosure section there we go we will close the opening nav link tag here and then we'll take the closing one and place it after the item name so there may have been a cleaner way of doing that but that works or else get rid of the disclosure button save and now check it out let's go to mobile hit this drop down and it looks right pretty cool now let's go ahead and fix this weird issue here where the page actually starts inside of the header so let's go back to the header and this is actually going to do with props.children so what we really need to do is we need to cut it and put it outside of this disclosure altogether but then we're going to have some issues so I'll show you how to fix that in a second But first you can find a little bit more information about disclosures from headless UI so it's a way you can conditionally open and close text here's basic example if you want to try it in your code we're not going to go through that right now but that's what our code is using so we just want it to be outside of that section and then we can only really return one tag so that's why we're going to surround all of this inside of a fragment so we'll go up to the top return we'll open it and then we'll take the closing one and put that down at the bottom so right after props.children paste that there save everything seems to have compiled nicely we'll go back to our site and there we go it's no longer embedded inside of the header so sorry about that that was kind of a mistake on my part the next thing has to do with this padding right here and you can see on the employees it looks okay but now we have this weird white bar what is going on so let's go remove the styling from this page and then add it to the header so we will go over to employees and scrolling down here this is another thing that I just didn't catch or didn't think of we have this class name app because we copied this over from app.js so this really shouldn't belong here we will remove those you can remove class name if you don't have anything to put there but we're going to move over to header and place that code here so let's surround this in a div class name and then I'll put the closing div here as well now let's just go add in the class name so I'll paste this we don't need the app that doesn't belong here that belongs in app.js so we just want a background gray of 300 and a minimum height of the screen size so going back to our application it looks exactly the same which is fine because really all we did is we just moved these classes from the inside component and moved it to the header now we can just remove that margin from employees which is to find right here margin Y 2 remove that that should move everything upwards now we can add that padding to the menu to control the spacing of whatever's inside so we'll go over to the header and add a class here we can say padding X to and padding Y2 and you'll really be able to see this well inside of this customers page where the text is now spaced out really well whereas before it was touching the side here and touching the top here really didn't look well now any kind of pages we put inside of this header is going to have that padding and should look pretty nice I think it looks best when it's zoomed in just a bit you might need to adjust styling as sizes change for example this kind of weird looking over here so I imagine you could cap the width to this here and then everything would fit within that section and you wouldn't have things just forever expanding to fit the page so if you inspect this area and let's just zoom out a little bit we open the nav we have a Max width 7xl so there's a good chance we could apply that to this section as well to restrict the sizing and then that might look a little bit more appropriately placed alternatively you could remove that class as well possibly let's just try it see what it looks like we'll go over here say Max width 7xl save now we just add a margin X Auto save that puts things in the center and then I think we can copy this same setup or we have the nav with an inside div and then the outer nav is what actually has the background color let's just try it so we'll go in here and Surround this with another div and this is the one that's going to contain the color so we'll say class name is equal to background Gray 300. removing that from this one which has a restricted Max width here so let's check that out there we go looks a whole lot better now it's a little bit more predictable in size as we zoom in and out and we don't have page widths that are like thousands of pixels perfect like I mentioned this video is just a bunch of cleanup and you know reorganizing our code a little bit nothing major when it comes to react this was mostly styling but in the context of react so you know it makes sense to have in this series if you got lost or your site just doesn't quite look like the one here and you want to follow along exactly well in the next video you can just pull the code at that exact moment in time and that's the code you can build off of for the rest of the videos so you might need to get some practice with Git for that but I will show you the commit hash and the URL so I'm going to commit both of these files and I'll just say that the commit message is mobile styling there I sync the changes and you can see that it's mobile styling here's the commit hash and then you can find the url right here so if you visit this URL you can get clone this URL and then say git checkout and then the first few characters of the commit hash alternatively you can go to the history here find the one you're interested in and view the code and that will allow you to go in here and copy any of the code that you need if you weren't able to get it working correctly well I think that is enough rambling for one episode so stay tuned for the next episode for continued rambling and if in case you're wondering what we're going to learn next it's all about use effect which is a very important part of react and we're going to use this to eventually fetch data from an API and make more interactive applications thank you I'll see you in the next one foreign [Music] behold one of the most important videos in this series and that is your introduction to use effect if you followed the series from the beginning great but I assume many of you have not been following from the beginning because your first time learning use effect is a little confusing did a little searching on the internet and now you're here that's fine because we're actually going to be starting kind of a new little application so you can follow along with this video just fine now it might not look exactly the same because we're using the template from the previous videos but all the concepts in this video are going to be fresh put simply use effect allows us to have some section of code that will execute anytime our state changes in addition it'll run after the page is initially loaded so once at the beginning and then anytime the state changes we can be a little bit more strict about when this code should execute so it doesn't have to execute all of the time and we're going to learn about those options in this video I think when I learned use effect for the first time I was confused mainly because of the name what what's an effect what does use effect mean and you can think of the name quite literally think of a side effect this is something that happens when you do something else so when you change the state of the application we have side effects that are executed and to do that we use the use effect hook so when you do things side effects happen right if you are in class you punch your teacher in the face there's a good chance you're not going to pass that class or you know you take some drug you may have side effects so you take a drug for heartburn but side effects may include abdominal pain headaches or heartburn nausea and vomiting diarrhea organs spontaneously exploding lizard skin laser eyes laser toes allergic reactions to oxygen and death coming from the react documentation mutation subscriptions timers logging and other side effects are not allowed inside the main body of a function component return return referred to as reacts render phase doing so will lead to confusing bugs and inconsistencies in the UI so what that means is all of these things we need a place to put them since they can't go inside of our function directly that's where U's effect comes in use effect fires after layout and paint during a deferred event so after the page is loaded this makes it suitable for the many common side effects like setting up subscriptions and event handlers because most types of work shouldn't block the browser from updating the screen a bunch of words to describe that use effect allows us to execute some code after the page is loaded and this code is not going to go in line directly inside of our function component instead we're going to move it over to use effect now let's talk about how to actually set up use effect what does the code look like and if those words didn't really make sense we're going to go through some examples to make it more concrete so we're going to start with a fresh component we've worked on some of these other components but we're we're just going to create a new one because I want to work on a new type of application that's kind of Irrelevant for the employees or the customers so we're just going to create a little Dictionary app so we'll call it dictionary.js and we're going to say export default function dictionary and we're going to keep this pretty simple what I want to do is I just want to have a state variable and then we're going to take that value from input and display it on the page so imagine you're typing in some search word and then the search we type shows up on the page somewhere so to use State we're going to create an import import use state from react and then let's create that const here so word and then set word so that's the word we're trying to get a definition for and then that'll say use state so anytime we want this value to show up on the page and to be dynamic we're going to want to put it in a state variable like so now let's display it on the page so we will say return we'll create a fragment and inside of here we're going to have an input so input type is text and then on change is where we're going to tell it to update the state variable so we'll just leave that like that for now and then we will close the input we'll fill that in in just a second let's just go ahead and create the text so we will create an H1 or whatever you want and we'll just say something like let's get the definition for word all right now let's update the state so we will just create an arrow function here so the parameters which we'll call E for event and then the arrow and then the curly braces which is where we Define what happens we'll say set word and the way we get what we typed in is e.target.value and that should do the trick so pretty simple page now we just need to set it up so that we can visit this page so for me and my application I'm going to go over to app.js and add a new route for this so route path is equal to slash dictionary and the element we want to render is going to be the dictionary which we want to put in lesser than greater than sine so dictionary looks like it imported it for us and then last thing I want to do is actually want to make a link to this in my header so it shows up so we're going to go over to header.js and just change some of our links here so we'll change this one to dictionary and this is going to 0.2 slash dictionary perfect that should be everything so let's go back to our site take a look this updated a dictionary uh what's a really complicated word we can get the definition for oh maybe something like subscribe yeah that's nice so definitely look up what that means and do it so now let's talk about use effect for this we're going to inspect and we want to confirm that something happens in the terminal every single time the state changes so for now we're just going to console log but later you can do more advanced things so let's head over back to our code we're going to go into dictionary and now let's add use effect so it's actually going to come from React 2 so we can just put a comma here use effect and this is a function and the way you use this is going to be different than use state so we're not going to assign to variables we're just going to invoke the function like so and this function takes two arguments or one the second one is optional and we're going to talk about when you want to use it so let's just start with the first argument which is actually a callback function so a callback function is a function passed into another function so you can just do an arrow function and Define it right here so parentheses Arrow curly braces and then inside of the curly braces we're going to say console log State updated and for fun we can display the state variable that we have all right let's check out our site and at this point let's do a refresh the value is currently undefined we can give it a default value whatever you put in here is the default so for example if we said help well that's going to show up by default let's just go ahead and use an empty string for now and now anytime we type in here the state updated is printed to the console this should happen even if the state is not being displayed on the page so for example if we went back and we just removed this for a second well now even when I change the value here it's still printing in the console so let's go ahead and put that back now again use effect should execute once on page load and then once for each change in state but you'll notice there's two here and I believe this is directly related to strict mode which is defined inside of index.js so if you have strict mode enabled there's a good chance you're going to see that twice on the initial load so let me change that and refresh and you can see we now only see it show up once so strict mode will render your components twice and do some kind of magic to check for any kind of issues so I'm just going to put that back as it was it's not hurting anything just know that in development you're going to see that on here twice coming from the documentation strict mode can't automatically detect side effects for you but it can help you spot them by making them a little more deterministic deterministic meaning that given the same input the same results happen which is an attribute we want to have for our code so that is why it executes twice but that shouldn't happen in production so it's okay to leave that and just have it execute twice in development now I want to talk about how this is different than an event handler where sometimes you can do the same thing so in our code let's go back to dictionary JS so inside of use effect I'm going to take this console log and I'm going to cut it and I'm going to move it down here after set word when we save and let's take a look at the console now it's going to be pretty similar but it'll be a bit different so we type in Caleb and it says State updated KO first off we didn't get that initial one on page load there's nothing there and it seems like the state is one character behind so what's going on well it's important to note that these set functions are asynchronous so they're not guaranteed to have that value immediately after on the other hand use effect will depend on all of the state currently and we can be sure that the state is updated as this executes after the state is updated so it makes more sense to move this console log up into this use effect and in the next video I'm going to be talking about how you can limit what state use effect cares about and this is done with the dependency array which is the second argument we pass in and that's just because we have already talked about quite a bit in this video and I also want to mention one more thing which is the importance of where use effect is defined so we want it to be within our functional component so make sure you define it inside of these curly braces and not outside secondly I like to Define it after any state and this has to do with the dependencies as well as if this depends on any state we want to make sure we have those values defined in our code and we're going to elaborate on this in the next video if we place this here and pass in a second argument which is an array and we put our word variable here going over to our code we're going to get an error in the console because word has not been initialized so if you just want to avoid that error always then all you have to do is just take this code and just make sure you define it after any state now you'll never run into that problem so if that was confusing and you weren't really sure what we were doing with that array well that's what we're going to be talking about next so make sure you stay tuned for the next episode once we have a good understanding of the dependency array we'll be able to use use effect to do our initial fetches for our page so that way we can grab information from a backend API and display it in our web page so we'll be going through that in the upcoming episode so stay tuned I'm getting pretty excited because we are starting to see things come together and we're able to make some more interactive web pages thank you I'll see you in the next one [Music] hey what's going on everybody this video we're going to be talking about the dependency array for use effect this is the second argument you can pass the function and the short version of what it does is it allows us to restrict what state we care about for use effect to be triggered so if you need the basics of use effect check out the previous video if you already got a little bit of it figured out maybe you just need a little bit more practice this video should probably be good so let's first just take a look at what we have which is if you don't pass anything at all as a second argument so here is our use effect function it just console logs that the state was updated and then displays the state variable and there's going to be really like three different ways of doing this so I'm going to actually summarize these in the comments below so the first one is if you pass no dependency array and in this situation it's going to update for any state change and we saw this in the previous episode where any anytime we search for a word it executes that use effect callback function this kinda illustrates the point but the way to really see this is to actually have more data in state doesn't really show us much if we only have one variable here so what we want to do is create another state variable and we're just going to call this word to and right now our examples are kind of made up and silly but in the next couple episodes we're going to get a little bit more concrete and start building some stuff but we just got to get this foundational stuff out of the way so we're going to pretty much Define it the same exact way and similarly we're going to allow an input to define the value and display it on the page so let's go ahead and copy this input and the H1 here we'll paste it again and we're just going to modify the data and of course we can have two H1s on the page come on we're not barbarians here let's go ahead and update these to H2 and then we just got to update some values so e Target dot value for set word two instead of set word one and then we're going to display set word two the last change I need to make is actually update the console log to display uh actually a space and then word two all right now all the data in state will be displayed whenever we update the state so let's just refresh and we should be able to search a word up here in theory so we'll just say fridge and it updates now let's try down here microwave spot it wrong but yeah you guys get the point microwave you can see this executes anytime we change either of these inputs so that is if you don't pass any dependency array the next option is if you pass an empty dependency array and in this situation it's going to execute once so let's try this out to do it we're going to put a comma after our callback function and put an empty array we'll save and I'm going to refresh the page and it has State updated twice actually here as a reminder from the previous video we mentioned it might show up twice if you have this strict mode on and you're in development so don't worry about it it'll show up twice for that situation but really you can think of this as executing once and if we update any of our state variables you can see nothing shows up in the console it's done so I would say you can use use effect with an empty dependency array if you want to do something on initial page load after everything is loaded and set up properly then you can execute some code for example we will probably have this set up when we want to fetch some data to put inside of our web page we only need to fetch that data at the beginning of the page load and then we can just substitute in the values that are returned from the API into the web page now the third option is if you have some values in the array so for this one let's just go through the example of passing in word we'll save and we'll go back let's just get a fresh start we'll refresh when we put in something in the first input such as headphones you can see this shows up a lot over on the side if we go over here and update word two screwdriver well the state changes but use effect is not executed that's because it's only going to execute when the word state is updated now a quick note and most likely it's not going to be a big issue but because this depends on word we can trust that word has the most up-to-date value but it does not depend on word two so this could in theory be outdated since the set functions are asynchronous as mentioned in the previous episode so in this situation use effect is only going to depend on one state variable and that is word so what we can do is we can still change this value up here and it'll still put screwdriver even though it's word number two over in the console here so let's try it out let's change this to shoes and you can see it shows shoes and screwdriver and screwdriver I had plenty of time to update you know computers are fast so for us to go and change screwdriver and then change this one well it's just too fast screwdriver has already been updated so again in this situation it's not a huge issue but it's just good to know that use effect is not going to wait around for word two state to be updated now the next important thing to know is that you can have use state in your code multiple times with different dependencies so what we're going to do is we're going to have use State dependent on word one and then we're going to have use State dependent on word two so we will take this code and we're going to duplicate it and I'm also going to update our comment here so passing in data this will only execute when those State variables are changed all right so we have one for word which I'm just going to get rid of the second variable here so word and then we'll have one for word two kind of had this displayed weird there so we use a plus here all right cool let's try it out window you can see it says State updated window and then we could say chocolate and it says State updated chocolate these are two separate functions being executed you can see this one's defined on line seven and this one on line 11. so this can be done for separation of concerns if you have one used state to take care of one Concept in your application and then you have another use state to take care of something else or for example maybe you want the initial page load to do something special but then every other update after that you just need something different so you could have use state with an empty array and then use state with some dependencies or no dependency array at all so that is all for my use effect summary there's one thing that will get an honorable mention but we're not going to explain in this video and that is use effect cleanup taking a look at the docs there is a section on cleaning up an effect and this is where you return a function and this will run before the component is removed from the UI so definitely read into this if you're interested but we're not going to be using it right now maybe later in this series I just want you to know that it's a thing so if you see use effect returning a function like that that's what it's doing next up we're going to take the principles we've learned and these couple last videos and start building an updated application to search for terms and get a dictionary response so this is is going to use an API so we're finally not just using mock data we're actually going to consume data that's coming from a back end so this is going to be pretty cool I'm really excited and hopefully you'll stick around for the next video after you smash that subscribe button of course thank you I'll see you then [Music] what's going on everybody this episode we're going to take the knowledge from the previous two videos and we're going to start building a new web page now over the next couple of episodes we're going to be doing this so it's probably not going to be like perfectly clear we're going to do this in episode one this and episode 2 episode 3 but I'm going to try to keep it organized so that we have some logical Concepts split up across those videos so this episode our goal is to use use effect with fetching data from an API so we're going to do this to get the definition for a word in the next episode I want to talk about how we can create individual Pages or parameterized pages so that we can basically create a page and then just change the information that shows up on that page and the change the actual word that we're searching by changing the data passed into the URL so it's going to be pretty ugly until we get to The Styling but you already have to see me in each one of these videos so it's not going to be anything you're not used to and with that let's get started so we are going to start with a commit message basic use effect practice so that is the commit message if you want to jump into this section here is the repo URL so I Envision that this dictionary page is going to kind of be like a landing page for our dictionary functionality so I'm going to keep all of this functionality here for now and I'm actually going to create a new component so actually this dictionary should be in the pages actually so we're going to move that there yes update Imports so the dictionary is going to be the page and then we're going to have yeah I'm going to make another page so this is going to be for a definition dot JS and I'm using the separation between components and Pages kind of lightly like don't overthink it a page is really just a component but it kind of gives an idea of how it's supposed to be used so the definition is kind of going to be its own component versus a component that's embedded in other Pages alright so we'll just go off of that so we'll say export default function definition and then we'll just return something like here is a definition let's go ahead and import use effect from react alrighty now let's go ahead and Define a call to use effect here pass in the first argument which is a function and I'm going to have this execute just once so we're going to leave it as an empty dependency array and we will just say something like page loaded and we'll console log this so obviously we don't just wanna put a string here now over in app.js we have the import for the dictionary updated I'm going to add a new route so route path is going to be slash definition the end goal here is to parameterize this so we can have some information after this of the word that we want to Define for now we're just going to just go with definition and we'll fix that here shortly but we have a few other things we have to build up to that so let's be patient definition beautiful beautiful and then from our website you could make a link to it but I'm going to ultimately get to that page from this dictionary page so for now we'll just go to slash definition here is our definition and we also see the page loaded showing up in the console so our use effect is working now we can do is we can go to definition close others and this is what we're going to be working on for a little bit so let's create a state variable so we'll say import use State and use effect and we'll Define the state first thing sub const and this is going to be the word that we want to Define and then set word and this may actually end up being an object full of a bunch of stuff such as the word the definitions synonyms whatever else it might be so we'll just say use State and we'll just leave it undefined right now unless we need to change that later so we are going to be using a free API on the internet that doesn't require an API key and this is an important note so oftentimes for a really good API you'll need a key and this will basically be your identity it'll prove that you have access to use this API an example may be this words API on rapid API you can use this for free up to a certain number of requests per day and it's a great way to get definitions so you can go in here and grab words and then go into like with the word and here is an example response so the word example and they have some more definitions down here the problem with this is that requiring a key makes your front end application insecure you don't want to give that key out because then people can use the API as you ultimately costing you money so the solution to this is to use the API key on the back end of an application and then connect to the back end that way the key is secure but that's kind of a problem because I'm not really to the point of building a back end if I was going to go through that process I might just build my own API and maybe we'll do that upcoming soon so for now instead what I want to do is I want to use an API that doesn't require a key in this situation we could use it safely from a front-end application because anybody can use that same URL without a key so there's no risk of giving out anything private I don't know if there is a good way to secure a key on a front-end application so an alternative is this free dictionary API at dictionaryapi.dev and I was testing it out seems pretty good so you can copy this link and then paste any word in here such as mechanic and the definition is someone who builds or repairs machinery and so forth because all we have to do is access the end point we don't need a key it's much easier to use and we can check all of our code into Source control without any concerns of keys getting out there or Keys getting exposed through the browser so let's talk about how we can make a request to this API using fetch fetch is one way of making requests inside of react and there are a few others out there but we're going to go with fetch we may look at some of the others later so here is some information on using the fetch API if you want to take a quick read it's going to follow this pattern so fetch and then two thens so we'll copy this and put this in our code we will get rid of the console log and paste this here now all we have to do is change this URL to whatever API endpoint we want to use so going back to The Free Dictionary API you'll want to go to dictionaryapi.dev and we'll just go with this link here so we can copy that and paste that here now hello is the word we're going to be defining we'll save and let's just check what shows up in the console log we'll head over to our site and you can see we do get a response here and it's quite some nesting so we have an array so index 0 and then inside of the property meanings we have another array of three so zero one two inside and that's for the different part of speeches so noun verb or interjection so you could grab one of those or all three you just have to decide what data you want from this so we'll go into one of these then we have another array of definitions and then the zero index here has the property definition so basically we're going to start with an array and we're going to Traverse this structure to grab the data we need so that might be a little frightening if you've never done this before but it's really not that bad you just have to go one layer at a time until you get what you want for example we could go into data and it was an array so we will grab the item with the index 0 save and now what is printed is one layer deeper so we're no longer an array we're in an object now we do the same thing for meanings so we will say dot meanings save taking a look now at the data again we're in another array and now we can choose another index so let's just go with zero index zero and so forth so that is how you will Traverse through the structure to grab the element that you want now you may want multiple elements very likely so what I'm actually going to do is I'm going to take all three of these parts of speech so we can just have all of those on the page so I'm going to back up I don't want to grab the item with the zero index there and just grab the whole array instead and this this is what we're going to put in state so not only will we console log but we're also going to do something else and you could just replace the console log if you want what I'm actually going to do is I'm going to surround this in curly braces and this will allow us to do multiple things so where do I want that curly brace we want it after the console log so right here and then we will space this out a bit like so so it should look something like this and now you can put other lines of code here to run in addition to the console log if you're only executing one thing you can drop those curly braces and just put it how it was but instead of console log do something else but we're actually going to assign this to set word and we want data zero Dot meanings we'll save and we can now use this word variable the state variable down here in our print so let's go ahead and change this up a bit we will make this in each one it could be plural singular whatever I'm not going to worry about it and I'm also going to do the multi-line thing here so I'm going to make a fragment and then close it off with a fragment as well so it'll look like this and I'm going to get rid of that semicolon since the return is now closed down here now we can iterate through all of those meanings displaying them on the page so that's going to be a very similar structure to what we did with employee where we did employees.map and then each employee gets assigned to this parameter here we're going to do the same thing but for definitions so if you want to try it out give it a go but it's going to look something like this we're going to have curly braces word dot map and this will take a function as an argument so make an arrow function here the parameter will be the meaning and then the curly braces is what we want to do so we will say paragraph and we'll pause here so we'll save and let's take a look real quick oh and I will want to return let's take a look real quick at the console so this is what we want to grab we want to grab the first iteration it'll be this one so definitions then is index 0 and then definition so let's try that it will be meaning Dot definitions index 0 dot definition lowercase D all right let's try that and take a look we get some information on the page so that is how you can define words let's try a different word let's go with helicopter check out the page it's an aircraft or to transport by helicopter so this would be the verb version so you would helicopter somebody and what we can do is we can put that here so meaning dot definitions of 0 Dot and let's take a look at the structure real quick part of speech is what we are looking for the dot part of speech and then you can put a colon here so we'll save that and uh it's not quite what I wanted um with the colon work there yeah I think this is right just not getting quite what we want here so it's actually not defined inside of that array there so I just need to remove that array it's really easy to get lost when you're doing this trying to Traverse through a complicated structure I do it all the time so I end up just changing things until it works so there we go we got a noun and verb let's just clean up the formatting just a bit there save looks a little bit better maybe a space after it's removing my space we can just do a plus a space there that should work noun and a verb so that is how you display data from an API last thing I want to make sure we get rid of this warning here we want to make sure each list item has a unique key so we will just use a unique identifier as we have done earlier in this series so using the uuid npm package here is an example you can find so import V4 as uuidv4 from uuid we will paste that at the top of our page scrolling back down we will just say inside of the paragraph key is equal to uuid V4 and now we should be able to refresh our page without oh my golly so this is actually a different problem it's probably good we ran into this you see we are trying to display all this data but maybe our API request is not yet finished and we're trying to you know Traverse into it and it's just not going to work out well so what we want to do is we want to create a ternary so if word is defined we're going to do all this otherwise we will just return null now we save and the page looks a lot better it's working we're not getting any errors on display and if it's going really slow it'll just be blank for a moment before the text shows up so you could try putting something like paragraph loading however it may cause some flashing of words like it'll just be there for like a fraction of a second in our case so it depends on what you want if you want that to be there or not I don't really like it I think it's just kind of like oh what was that I didn't get to read that so I'm just going to return null and we still got this uuid here working so everything seems to be good that is the general structure for requesting data from an API and displaying it on the web page after the data has been loaded up next we're going to talk about how we can modify this page so that we can search any word and not just a hard-coded value to find in the URL here wouldn't it be cool if we could actually just paste it in right here so I could go in and type cucumber for example and it would look up the word cucumber well right now it just shows a blank page that's because the request fails and never does return good data and this evaluates to false so that's what we're going to talk about in the next video which is going to be about URLs and parameterization stay tuned and thank you for sticking with this video series so far hopefully it has been really helpful and at a good Pace to pick up this stuff I've been trying to show my common mistakes and not be like 100 perfect so I hope that's not too distracting and rather helpful but definitely let me know in the comments section if you like the way this series is going thank you I'll see you in the next one [Music] hey everybody this episode is going to be really cool because we're going to use another hook in this episode which is called use params and this is used to pass parameters through the URL so we will learn how to parameterize our URLs and make our component more Dynamic a bunch of jargon words to mean that I want to throw a cucumber in here and get a definition for it and right now it's just giving me this gray screen which is lame so what do we need to do well anytime we're going to be working with URLs we go to the routing section of our code and we're going to define a route very similar to this one we're just going to change a little bit and that is going to go right here so we want to be able to put a slash here and then some word to search for in the dictionary and I'm going to call this search so you prefix it with a colon and then whatever you want to call that data and we will be able to get that data inside of our component now I was going to call this word but I decided to call it search instead and you'll see why here in a second let's head over to the component definition and you can see we already have this word variable here so I want to use a different word besides the word word I was confusing you guys know what I'm saying so what we will do is we will say import use params and this one's going to come from react router Dom and we can get the data with destructuring so it's going to give an object to this component and we can destructure that with curly braces so we can grab a property on that called search and then we'll say use params so if we just wanted to see we could say console.log use params and let's take a look at our site it will have an object with just one property search and you can see it has the value cucumber which comes from right there if we change this oh man we're thinking of words it's like the hardest part of this series paint it'll change that value so we're going to just assign it to this variable called search and that's why I didn't name it word because we already had word being used and now we can append the value right here so we'll remove helicopter and replace this with search let's save test this out so we could type in paint oh it's already working a substance that is applied as a liquid or paste and dries into a solid coating that protects or adds color slash color to an object or Surface to which it has been applied or to apply paint to I don't get why you guys from not the US use a u for color now we can actually search so let's see what happens when we say color the spectral composition of visible light I wonder if it's exactly the same if we change it to color yep but as we can see the definition uses c-o-l-o-r so it's just a matter of fact that this is the correct spelling as a side note you can use the network Tab and you can see where that request was being made and a response here so if you're having issues you can always check the network Tab and make sure your request is going through correctly and this is totally unrelated but one thing I just want to increase this padding just a little bit just because I feel it's a little crunched this is really just for those of you who have been following along exactly so we will head over to the header and find where we have our section and padding X we're going to increase that let's see what 4 looks like Ah that's a little too much gosh I should have known dang it all right three that looks great and at this point I think we're safe to remove our console log we're not going to need that for now and there you go one of my next goals is to build search capability which is going to use a couple more Hooks and some other functionality so hopefully that sounds cool to you that way we don't just type it into the URL but we actually have a search bar that can then go and grab the right definition thank you for watching be sure to subscribe if you've enjoyed the content and see you in the next episode foreign [Music] everybody this episode we are going to learn a new hook called use navigate this is really cool because it allows us to force the user to visit a new page on our application however it's different than a link a link the user actually has to click whereas use navigate we can put this inside of event handlers so what we're going to do is we're going to create a search bar user type something in slaps the search button and force them to go to a new page now if you are coming from an earlier version of react router you might be familiar with use history or you might see that floating around well use navigate is the newer suggested way of doing this and is the only option available in the newest versions of react router so use history use navigate pretty similar probably good to be familiar with both but use navigate is the way to go in the future but before we get started in the code be sure to subscribe as we navigate our way to a million subscribers man that was good so we're going to start here in app.js because I wanted to call out a few things in earlier videos we created this parameterized route where we can pass in the search term and we also have this definition page without the parameter so what I think I'm going to end up doing is I'm going to have this dictionary page which is going to kind of be the home page and have a search bar and then when we visit a definition we're actually going to use this route down here so this definition route without any data passed in is no longer necessary we're just going to remove that and what that means is we are required to pass in data for example if we go to localhost 3000 slash definition by itself we don't get anything on the page and we'll talk about 404s here soon but this will work for now so we'll start on the dictionary page we can type in something we'll search for it and then it'll go to a definition now I already have some starter code here but if you're just jumping in no problem because we're pretty much going to get rid of a lot of this so what we'll do is we will go into the dictionary component and we're no longer going to need this for word two where I had two of them there so I will remove that input and also remove the repeating the word that they're searching here so now our page is going to look just like this and we also have these use effects up here we're not going to need those for now so we'll remove those and remove the other word that we're working with so yeah if you're just jumping in this is the code that you want to have and if you're following along you'll probably just want to delete what I just deleted so we're all on the same page so this is what our site looks like pretty beautiful and just as a reminder we're going to worry about styling at the end so let's just get the functionality figured out what we're going to do is we're actually going to not only have an input but we're also going to have an HTML button and this is going to have an on click and we'll make this button say search so now let's go ahead and fill in the on click with a function and console log IC save and now let's check out the console when I hit search you can see the value showing up over here so the event handler is working and now let's talk about how we can navigate to a new page using use navigate so first thing is we're going to import it from react router Dom so import use navigate from react router Dom which you will make sure that you have that installed it is something that is a separate dependency so you'll just want to say npm install react router Dom if you don't already have it now we're going to create a reference to it similar to how we did use state but it's going to look different because we're not going to have two variables here so we will just say navigate is equal to use navigate and we will say const navigate and then anytime we want to work with the URLs we're going to use this navigate variable so let's go ahead into this button click and we'll say navigate and then pass in a path such as slash definition slash all or just hard code a value right now tacos save and we'll go back hit search and it goes to the definition of tacos pretty sweet from this point we should easily be able to substitute in the value that we're storing inside of this word state so we probably could have just done that to begin with but we can just say Plus word and now we can search whatever we type in Texas hit search oh no undefined reading meanings what what in the world let's go to network let's check out Texas it's responding to 404 so it doesn't appear they have a definition for Texas so we're going to worry about that soon like I mentioned 404s will come after this functionality so 404 means the resource wasn't found and that can be one issue we run into another one is it's unable to connect and in that situation we're not going to get a 404 so instead of saying definition not found we might want to say error connecting we're going to talk about that but so far so good let's try it with an actual word that they understand maybe pool and there you go you can now use this as your personal dictionary if you want to just see the code for how this definition page is working real quick go into this file definition and we're just calling that directly with the search term and then we're just traversing through the Json structure to set the word which is then displayed on the page they give multiple definitions that's why we are iterating through each one of them so not too bad just wanted to throw that in this video for completion's sake now I want to talk a moment about history what happens if we hit the back arrow right now we hit back and it goes back to the dictionary page as you'd probably expect that being said we have the option of passing in an additional object here with some settings so we could say replace and set this to true so now let's go search a word such as replace hit search the URL changed here but if I go back you can see it goes to a previous page so what's going on here is that it's replacing our current spot in the history that's all I got on use navigate in this video if you want to do continued research I suggest looking up redirects how to do those because you can redirect if a page is not found or you might want to learn how to display content on that page versus redirecting so showing the 404 on that page or showing an error if something goes wrong that's what we're going to be talking about in the next video stay tuned it's going to be so exciting see you then foreign [Music] so far we have been building our application as if everything is being used correctly and things are working but what if things go terribly wrong we hit a 404 or we can't connect to the server right now our application just breaks it doesn't do anything as shown before we search a word that doesn't exist and it just it gives us a blank page not very friendly so what we want to do is first deal with 404s and the way we're going to do this is by creating a 404 component inside of our component list that we can redirect to when we hit a 404. alternatively we can show the 404 component in line if we don't want to have a redirect but let's start with the first one so how do you check for a redirect this response here that we get inside of fetch actually has a status code we can check so to do this let's go ahead and wrap this in curly braces and when you do that it allows us to write across multiple lines so we can expand it like so and then we would just change this to return response.json this is just an alternative syntax to the arrow function it does exactly the same thing but now we can go in and add another line here so let's go ahead and console log response dot status saving this let's give it a try oh you can see right there it already says 404. building off of this we can make a condition checking what status this is and if it's a 404 do a redirect so let's try this first let's just create the if statement so if response dot status is equal to now I can't quite remember if it's a string or a number so what we're going to do is we're just going to try it as a number first and see if we get the console log and it looks like it is in fact a number so not a string so this is exactly what the syntax is going to be and instead of a console log here we can actually redirect now the way you redirect now is with navigate which we learned about in the previous video so this is a perfect example of where you might use navigate so let's go ahead and say navigate now we did use navigate in the previous video but it was in a different component so every time we reuse that in a different component we need to do the same thing we have to import it and then invoke it setting the return to a variable so it'll look like this we will say import use navigate and then create a reference to it by invoking it with use navigate and we will just say const navigate all right so that's the syntax and then down here we can invoke our variable and pass in a path such as slash 404 so let's try this out we'll save and it already worked but let's go back to the dictionary just to see it from the beginning so we'll go to dictionary type in some word that the dictionary doesn't know hit search you saw it quickly pop up something about a definition and then it redirects to a 404. so a couple of issues we should probably fix so it doesn't flash that text and we don't actually have a 404 page so first problem is the text popping up so this H1 we can take this and we only want to return it if the word is evaluated true now we're going to be returning two things from this so let's surround it with a fragment so it'll look like this and then we just need to wrap this in curly braces like so now we should be able to go in here and add the H1 save does a little bit of a reformatting and this is what we get so let's try this again we'll go back to the dictionary search something like Texas hit search we don't get anything pop up on the screen which is good now let's go ahead and create a 404 component you could create it as a page as well but I'm going to create as a component because then you could in theory embed it in other Pages which you can do with Pages as well but just logically makes sense to have it as a component here so 404.js function and I'm just going to export it here so export default function and we will call this can you start a function with a number I don't think you can so we'll say not found and I'll just keep the file name to match that for consistency so not found.js and here we will return paragraph saying resource not found it's kind of a techy way of saying it which you might want to make this more friendlier so the page you are looking for was not found that's a little bit better now so I'm not going to work because we haven't Associated that component with this URL so we have to do that in our routes which we defined in app.js so let's go ahead create a new route and this one is going to be interesting first we will create a route for slash 404 and the element is going to be the 404 component so just invoke that here 404 or I guess it's called not found this will need to be imported so import not found from dot slash components slash not found all right so I got that imported so now we should at least see that show up the page you were looking for was not found however we also want to redirect potentially if we type in some garbage here and it doesn't go to a page that exists we can redirect to a 404. so basically we just want to make a catch-all for the paths and we want to put this last so we'll say route path being equal to anything which you can say with an asterisk element is going to be the same thing the not found component all right so basically it's going to go through each one of these paths if it doesn't hit anything this one should catch it but let's just try it out to make sure slash garbage does in fact show the 404 not found you'll notice that the URL doesn't actually change it just shows it in the page we can do the same exact thing for our Search terms if we want so let's go to the dictionary again type in some word hit search if we want that to stay Texas up there then all we need to do is we just need to embed that component so we'll go over to the definition scroll up if respond status is 404 we will set a state variable of not found to true so const not found set not found is use state and we will just set that to True here so by default let's make it false so you can pass that in here and then here we will say set not found to true so far so good and then what we can do is we can actually check that value down here so if set not found and I'm bringing my terrible python habits here so if set not found is equal to true then what we want to do is return not found and I'll make that self-closing and we'll make sure that that is imported so import not found from dot dot slash components not found and we'll search Texas his search didn't quite work just typo here I said set not found equal to true we want this to be not found there we go now it says the page you were looking for was not found so this is kind of interesting where we have a return here and then we have a return here and basically as this component continues to be updated as the state changes it will return the appropriate thing let's try a different definition seems to work I also think it would be appropriate to have a button to go back to the dictionary so if you do search something that doesn't exist it could say something like search another term or again you could create a search component which is embedded here let's just create that button so what we'll do is we will go over to this here and what we're going to do is we're going to surround this in parentheses which will allow us to write our return over multiple lines the very first thing is we will create a fragment which is going to be the single thing we return but inside of that fragment we're going to put multiple things so we will put the not found component you could create a button that then navigates or you could just create a link component and set the path to slash dictionary and this I think we will want to close separate and then put the value that shows up here search another so this is going to need imported and like other things from navigation it's going to come from react router Dom so we'll say comma link let's try that out this page you were looking for was not found search another Cheetos search not found chips search and there we go so we talked a lot about 404s in this video took a little bit longer than expected so I'm going to talk about errors in the next video and this would be if say for example your internet is not connected and we can't connect to that back-end server or various other errors like that such as being unauthorized and so forth so you want to check out that video if you want to know more on making your application a little bit more interactive thanks for watching stay tuned and be sure to subscribe foreign [Music] welcome to this episode where we're going to talk about errors when it comes to web requests the previous video we talked about 404s you definitely want to check that out because this is going to be very similar you see there's actually tons of different types of errors that could happen 404 is actually one of them so that's a status code there are other status codes 500 being another common one and then there's a whole list of other ones that you can check for so here is a summary of the HTTP status codes they are in ranges so hundreds two hundreds three hundreds four hundreds of 500s 400 is being client error responses and 500s being server error responses these are the two that you need to worry about in this video so ours was a 404 in the previous video and you can see that's here but there are also others such as unauthorized bad requests method not allowed and a bunch of others it's up to the server to return the appropriate response so you can think of it as you make a request to the server the server is like no bro you're unauthorized I'm going to give you a 401 don't let it happen again in that situation there is something wrong with the client us we're the client in the situation we are not authorized so we need to get authorized by logging in or another example would be method not allowed we're using the wrong HTTP method those are client errors the next are server errors when you make a request to the server and it's like error cannot compute in that situation you're going to get a 500 message the most common one you're going to see is probably just 500 which is a general error but you may see some of these other ones as well so these are going to be checked inside of our fetch as well you can just create more if statements or else ifs so else if response dot status is uh let's go with 401 then you may redirect to let's say slash login else if response dot status is 500 then you might just do the same thing how we did set not found here you could say set server error to true these are some of the ways you can handle these different responses the absolute best way to test this is with a website there's probably a lot of them out there here is an example of one where we can make a request to this page with the error code we want to receive back to check that our response is appropriate or if you're working with a back end you are coding and you can control then you could do that yourself but let's go ahead and just try this out I'm going to copy this URL and let's go ahead and create a URL variable and I'm going to paste that here and then I'm going to make another URL variable and I'm going to take this here cut it and paste it here so now what we can do is I can comment one of these out and just pass in url here and let's go ahead and try 404 and we will console log response dot status and obviously we're going to need to get rid of any variables we don't actually have if defined so I was just using that as an example and yeah we'll go from there so let's try it on our site so 404 seems to be working pretty much the same way as it was but now let's try and change this to a different error such as 401 when we save we can see it redirected us to login so that appears to be working let's go ahead and try this with a 500 as well we're not doing anything with setting an error but we should still see the response status in the console as 500. so everything appears to be working and let's just try it out if we put some bogus URL here just for a second when we run this and we'll just do a refresh to get a fresh view here we get some other errors here but we don't get a status code so what we can do is instead of making a section for every single possible status we can make a catch all if something else goes wrong so to do this we can check if response dot OK and not only that but we want to invert this so if the response is not okay what are we going to do and now in here we can say set error and put true which we can create the state for this so let's go up here and we'll say const error and set error use State and we will default this to false so if the response is not okay we will set the error and what you'll typically see is throw new error and you can put a message in here like something went wrong this can then be caught down below this then so we'll say dot catch similar to then this will have a function which we can then console log and put in the error message so we can say e Dot message here and then we can do anything else such as retry or do some logging whatever we want to do and if we just get something completely off you know if we just put some bogus URL it'll just jump down here and give us the message so right now we get failed to fetch and if we went ahead and let's say instead of this bogus URL here we used this URL and got a different status code such as 501 now we'll get in the console something went wrong which is basically a way to say that hey we noticed something went wrong but we don't have a case for that situation so we just have a general error saying something went wrong and what we can do is show something on the page so scrolling down after if not found we will repeat this similar thing in fact we could probably copy paste this and now we can do is if error is true we will return instead of not found let's return a paragraph saying something like something went wrong try again now our page should say something went wrong try again at this point I'm just going to go back to the original URL and confirm that our page is in fact working and now what we can do is we can just remove this console log for the status and as you develop you can add any sections for different status codes you might encounter for the 500 you might do something similar so you might just say set error true and if we did end up getting a 500 we will get that similar response something the wrong try again but you could handle it a little bit uniquely depending on if you needed to or not so you only need to create the sections for status codes you want to handle in a unique way all right enough talking let's go back to how we had it seems to be working so at this point we can move on to the next video that is the basics of dealing with errors and Status codes inside of fetch basically this is a lot of stuff because there can be a lot of different error codes so what you need to do is you need to look at whatever API you're consuming most likely if you're building an application you will be building the back end or someone you know will be building the back end and you can see exactly what status code options there are that could be returned and then you can make a matching section of code on the front end to deal with each one of those individually pretty early in this series so we haven't quite gotten that far where we have a back end and authorization and all of that but hopefully we can get to that soon and I have a lot of other resources out there for backend development if you want to get some more experience but for now I recommend you just stay tuned in this series because we're going to continue learning and once you start working with your own back end having these skills are going to come in really handy hopefully that was helpful thank you for watching and stay tuned for the next one peace out [Music] what's up everybody this video we're going to be wrapping up what we've been talking about over the last few videos so we're going to be doing our styling some refactoring lots of cleanup on the user interface and overall just improve the user experience so lots of stuff in this video but we get to look forward to starting something new in the next video so I encourage you to follow your way through this video and go through these same code changes I have a way of when I'm explaining stuff to kind of go through some examples and not clean up after myself so now we're going to go through and clean up this search which doesn't work too great we also have some other things I needed to fix so the first thing is when you search a term let's go back and we'll search tacos or something first off the enter button doesn't hit search so you have to actually click it we're going to fix that next we're replacing the history so when I go back it doesn't actually go back to the dictionary page so we're going to fix that as well and then when you actually do search a word I want to be given the option to search another word in line here with a search bar so we're going to overall just make our application a little bit more user friendly let's start off by not replacing the history that's easy I went through this example but I never actually cleaned it up after so we'll replace that easy peasy now for this return inside of the dictionary instead of returning a fragment let's go ahead and return a form and give it an on submit event handler here so we'll Define the function and inside of this function we're going to do exactly what this button is doing which is navigating so cut this from the button paste it here and the reason I'm doing this is because by default when you have a form the button will submit that form and when you have a form selected you can use the enter key to submit it as well so it's an easy way to enable the enter key now we don't need this on click for the button we can get rid of that all together clean up this code just a bit there we go and we need to close the form down here as well so we save looks pretty good let's check it out we will search another term test hit enter and it works so that was a bit of functionality improvements that I was thinking about now let's go back and style this so it doesn't look like uh what's something that's super ugly well I've always found mirrors to be pretty ugly but anyways let's go back to this and we're going to style this form so we'll say class name we're going to use the flex class which makes it very easy for us to Center the content with justify Center and add space between the elements with SpaceX 2 for example save and take a look already looking a lot better now one thing I want to do is add a Max width of say 300 pixels and if you want to do a specific pixel amount you need to use square brackets like so what this will do is it will restrict that size and it also scoots it over because originally the width took up the whole page now the width will just take up this much of the page so 300 pixels and then within that 300 pixels these two elements are centered with a little bit of space between them hopefully that makes a decent amount of sense with how these classes work next thing you can do is give a placeholder to the input switch to me just makes it a little bit more predictable on what you're supposed to type in there or what people will type in there so for example we could say dinosaur and now we get a grayed out dinosaur text and then we type it will replace that it still looks a little funny in this box so let's go ahead and add some padding so we'll say class name and set this equal to p x two there we go that'll push over the text just a little bit next you may notice these Corners are very sharp you can fix that with the rounded class now it looks a little better the only other thing is maybe making it slightly taller so for that I'm going to add a p y of one let's take a look now ah yes that looks a bit better obviously this comes down to personal taste so you can design it how you please now if we take a look at mobile view if we scroll down you can see it gets cut off and there's an easy fix for this inside of a flex right here you can make your elements have the shrink class and this will shrink them when the screen size shrinks but we have to have one more thing and that is to set a Min width of zero because by default inputs will have a minimum width and prevent that from working so now whenever we scroll over this will shrink and the page just looks a lot better so now we don't have to worry about if someone's on a mobile phone it potentially being chopped off which most likely it's fine but it's just a good thing to know now I will talk about centering both of these on the page but first let's do the search button so I'm going to steal some of the classes from the ad employee which has these classes so the specific ones I want are the color and the hover the text white font bold and rounded I don't really want the padding because I'm going to use the padding to match the other input and we don't need it to be centered or block so we'll just take these and we'll just remove the ones that we don't need so you can just type them out if you're following along so we'll go down here class name paste and then we'll replace these with py1 and p x two all right cool let's check it out ah not too bad so that's what it looks like on mobile and then this is on desktop now the end goal is to be able to type in a word here and now there we go we got a dinosaur I want to have a button here with the search bar so it would kind of make sense to design this as its own component that we could include here or on the definition page so let's do that now we're going to go into our components new file definition search I'm not going with plain search because this is a little general and I could see me wanting to use that later but feel free to use that if you wish export default function definition search and now we're going to do is we're basically just going to take everything out of this dictionary here and we're just going to put it inside of the definition search so I'll take all this code here cut that paste it here and I'm just going to take the Imports as well so we'll take those and bring them up here and now we should just be able to return definition search and then close that we'll save and hopefully that works ah Yep looks to be exactly the same here but now we have a component that we can reuse so if we go into the definition after the definition is printed which is right here we could have another search bar so we could say something like paragraph search again and then include definition search let's check that out we'll search something there we go it gives the definition and then gives us the opportunity to search again I noticed one potential area of improvement is this spacing so we have it so that the elements here are centered inside of this form using justify Center there's an alternative we could use which is space between and that'll space them out but line it up on the left so let's try that out we'll go back to our code and go into definition search and switch justify center with space between and now it appears that everything is in line now it may be the case you want to Center this on the page maybe you don't that's fine but I'm going to show you what that might look like if you do need to do that so basically now that we have this component we can move it around as a single unit so we'll go into the dictionary page and we can surround this with a div so we'll say div and you'll notice everything's kind of grayed out that's because we need to put parentheses around everything and then we can remove the semicolon from the definition search and then we can give a class name to this div and the class name we're going to use we will use flex and then justify Center and you can see that'll put it on the center of the page so by putting this centering logic inside of the dictionary component instead of inside of the definition search it's a little bit more flexible now we can have it centered inside of the dictionary and not centered inside of a definition those are the major changes I wanted to show you there's one more thing I'm going to show you in this video which is completely optional right now we have this main page and then we have a parameterized page that takes data here and these have different values right here you could use the same thing so you could have dictionary and then dictionary slash hello and that's totally fine so if you wanted to set that up it would be inside of app.js or wherever you've defined your routing and we had something kind of like this originally with definition we end up removing it but now that things are kind of built out makes a little bit more sense to have this in here so now we have the dictionary and then when we type in something it goes oh we have to update the URL path so definition search and we will change this to slash dictionary let's try that so go to the dictionary hello and it goes to dictionary slash hello either setup works this kind of makes sense to me you know if we want to go back to the general dictionary page we just delete that extra section of the URL and here you might have some more information like suggested words or generate a random word whatever it may be another cool challenge may be to search and have the definitions show up in line here and you can keep getting new definitions showing up on the page and at this point I think we're good so I'm going to add everything and commit style the dictionary oh yeah get us all right so I'm going to push this and now we can all start on the same exact page in the next video If you haven't been following along exactly you can find the code with that commit title and find it at this URL here so yeah definitely check out the code if you need and with that I hope you're excited for the next section stay tuned and be sure to subscribe [Music] we have talked a lot about the front end in this series makes sense this is a react series but if you're building an application with react you're likely going to need to connect to a back end the back end is responsible for storing information in a database which is how your application remembers so if you log in and your website says hello Caleb at the top well that information is most likely stored in a database and that's why if you go to a different computer and log in it'll still say hello Caleb that name is not stored on their local computer rather it is stored on a server and we are just connecting to that server from the front end now if you are new to web development the way we split up the functionality can be a bit challenging to wrap your mind around but the important thing to know out of all of this is that the language or what framework we are using is less important than the interface between the different sections what what am I talking talking about well I could probably name off at least five different back-end Technologies but connecting to those back ends from the front end is going to be similar across all of them you'll probably not need to make a single change as long as you keep the interface the same so this interface is usually built using a rest API so the rest API is an agreed way of communicating that has the ability to get information add information edit information and delete information those four different things you can do are often called crud create read update delete and we can do those things no matter what back-end software we are writing so we can have a react front end and we could have a node.js backend or if I don't like that I could swap it out for asp.net which is c-sharp and the front end application is going to stay pretty much the same occasionally you might need to change a little thing here and there but overall the application is going to be split up across different silos and the only thing we have to worry about is how these things communicate so what we're going to do over these next couple videos is we're going to build out a back end and connect to it from our react application now I do want to make clear that this is not designed to be a back-end course but I think as a front-end developer you should have some experience in the back end and if you want to be a full stack developer you'll want to have a lot of experience in the back end so we're going to go over the basics and get a rest API created but if you want a lot of the details to you know be more advanced in backend software then I have a dedicated course to backend development and this is all in Python AWS and postgres database so if you want that extra substance you can check out that course so that course is at codebreakthrough.com backend hyphen Python and you can read through this why I think backend focus is really really important even for front-end developers and we go in a lot of depth on how to set up a proper python environment setting up a Bare Bones project working with data uploading files and deploying production databases creating apis and a bunch of other information which just realized I'm missing a title here wow that is so unprofessional I would never buy this and as with all of my courses everything is downloadable so you can watch it all offline but enough advertising do it right now what back end are we going to use well I'm going to use Django it's what I'm most familiar with and if you want the extra details with it I have the resources for you to learn but I do want to just make sure that I don't make you guys not want to watch the rest of the series if you're using node.js for example because the backend coding is just going to be a small section of this series and a lot of the different things are going to transfer between back-ends so creating an API is going to be pretty similar across these different Frameworks and programming languages a lot of people will choose node.js for their back end because it's in JavaScript so then you can have JavaScript on the front end and JavaScript on the back end I like node.js and I like Django and I have some experience in some of the other backend Frameworks but those are the two that I have enjoyed the most so that's what I would consider getting started with one downside with Django is we have to learn a little bit about setting up a python environment another downside with python is it's not perfectly the same across operating systems so so I'll try to do my best to make this Windows friendly as well but I am on a Mac but you'll go to python.org and you can download Python and get this version here so this is 3.10.6 if it's a slightly newer version it's probably okay to continue following along with this series if you are on Mac you can also use Brew so brew.sh and for this once that's installed you can say Brew install python now this tool is not available on Windows if you need more detailed Windows instructions I have a video python environment set up for Windows Mac and Linux this will get you started so that you can start developing in python or you can just follow along if you were able to successfully install Python and the way you're going to know that your environment is ready to go in the terminal you should be able to say Python 3 dash dash version on Mac or Pi dash dash version on Windows once you get a response with a version that means you have python ready to go and we can start issuing python commands so what kind of commands am I talking about well the first one is to create a virtual environment so what we'll do is we will CD so change directory to a location where we want to create our back end so I'm going to put this inside of my CS folder and I think this is where I have my react directory as well which is what we've been working in so far in this series so I will just say mkdir to make a directory and we'll just call this back end and we can change directory into backend good so far so make sure you are in this directory and we're on the same page here's my path should be pretty similar but you don't necessarily have to be in a CS director or anything just put it wherever you want and from here we're going to say Python 3 on Mac or Pi on Windows Dash m v e n v and then we're going to name the virtual environment I'm going to call it dot v e and V so that is going to create some files when we say LS we don't really see anything or dir on Windows I believe to show all the files so we'll say LS Dash a and we can see that we have this hidden directory that's what the dot does it's a great way to say that hey this is a directory you're not really designed to touch just leave it alone once we create this virtual environment we will activate it so on Windows you will say dot space dot VNV slash and then in here bin slash activate and when you do that you'll get this Davi and V over here on the left on Windows it's going to be Dot venv backslash source backslash activate and again I show this whole process in my python environment setup for Windows so try that out the goal here is to get this over here on the left hand side that tells us that we are in this virtual environment which reminds me I haven't even really explained what a virtual environment is it's the lens we look at our project through and it'll tell us what packages we have installed what versions to use for our application so typically you'll have a virtual environment for every project you build in Python I do have a video that's actually a preview from my course packages and virtual environments which will give you a pretty good understanding of virtual environments if you need a deeper knowledge but the main thing you need to know is it controls what packages to use so we have to make sure we activate it before we do anything like installing packages so to install packages you'll say python-m pip install pip is the tool that comes with python to install packages and then we will say Django so Django is the framework that we're going to use to build our back end all right good so far we have that installed and now we should have this new command Django admin and you can see it lists out different things and the one we are interested in is start project so we'll say Django admin start project and then a DOT to refer to the current directory so that's where we're going to place our files and one other thing I forgot is the name of the application we're going to use so we will just call this customers all right cool so at this point we should now have customers in this manage.py file for the rest of our commands we're going to use this manage.py file so what we will do is Python 3 manage dot py run server on the initial setup we will use this Django admin command start project which came from this list right here but this manage.py file will do pretty much the same thing but make it a little bit easier so that we don't have to do as much setup with these different commands so you can see that run server command is also in that list but now we're going to execute it with manage.py so hit enter you'll see this problem with 18 unapplied migrations we'll talk about that here soon don't worry about it for now we will have a running server at one two seven zero zero one eight thousand so we will go visit that address you can also use localhost 8000 and there we go we have the default Django web page so the backend is capable of delivering HTML like this but pretty soon we're going to replace this HTML with just plain Json data so it'll be more like this where it has data in these key value Pairs and then we will just read that data in our react application honestly not too bad we got a server set up and just one kind of brief video and we have a better understanding of how our application is going to be structured in the upcoming episodes we're going to work on setting up an API by default Django is designed for sending HTML if we want to use Json data we're going to use another tool so that's what we're going to talk about setting up in the next video but overall it shouldn't be too bad obviously if you've made it this far through this video you're probably following along with the python code but I do want to mention if you are comfortable with another back-end technology feel free to use that for this series you'll just want to make sure that the data being sent back and forth is the same thank you so much for watching stay tuned for the next episode I'm really looking forward to this section see you then don't forget to subscribe of course and if you need check out that back-end python course [Music] foreign this is when we are going to create our backend API this is the goal of this video and in the upcoming videos we're going to connect to it from react now this is a point where things get difficult and you've been sticking with it this entire time so I just wanted to give a little message of encouragement which is congratulations and thank you for sticking with this series I know it's hard but for once you're doing something with your life and there's just so much potential you're not quite there yet you're getting there so there is a chance if you stick through the series you will not just be that weak peasant that you've always been so hopefully that gives you a little bit of motivation to get through the rest of this series let's jump in and build that API and again thank you so much where we left off in the previous video is we created the most basic Django application the default application what we want to do is we want to first open it in Visual Studio code similar to how we have our react application here and then we want to get it up inversion control get it up on GitHub so we can save our code and then you guys can reference my code if you need any help or you just want to clone the project so to start let's open it in Visual Studio code and if you have your server running you can control C out of it so that will close the running process and then you can say code dot which is a shortcut to open Visual Studio code from the terminal alternatively if this doesn't work you can just open Visual Studio code from a new window file new window and then find that path but I'll use the code dot that's going to open a new Visual Studio code window and I wanted to show you if that doesn't work you can do command shift p or probably Ctrl shift p on Windows and then this is the command you're looking for so you can type in path shell command install code command and path so that'll create the code command and putting it in your path is what allows you to use it from the terminal so here are all of our files the way we created our applications not quite as nice as react where it already generates a git ignore and initializes a git repository so we're going to do that ourselves so we'll go up here go to new terminal and now we can do all of our terminal stuff from here instead of from here so you can just close out of this one perfect now let's go ahead and say get init to initialize an empty git repository this will start tracking 5000 changes which we don't really need all these so we need to create a git ignore so you can say touch dot git ignore or just create the file right clicking in new file but this is the git ignore we're going to find a good git ignore template on the internet which will only check in the most important files so when I look for git ignore files I'll just usually search get ignore for whatever I'm doing and I like to use top tool their stuff's pretty good and it's really easy just to copy paste that over here and they get ignore and you'll notice when you save this number is going to drop down to seven so now it's only tracking the essential files that we need in Version Control at this point we should be able to say git add dot which will add the current directory everything in it and then git commit Dash m initial project if this is your first time using Git You might need to do some setup for your username email All That Jazz you can also use this tab over from Visual Studio code if you are more comfortable with that now let's figure out how to push this code up to GitHub we've done this once already with react so go into GitHub and we're going to create a new repository I'm going to call this react backend Django I'll make this public for you and I will share the URL as well go ahead and Skip all the other stuff we'll take these three lines of code since we already created the repo locally here is the URL if you want to refer to any of my code so just slash Caleb Curry and then slash the name of the repo all right let's go over to the terminal and paste these lines what these will do is rename the main branch if it's master and then it'll track a remote Branch up in GitHub so now at this point we should be able to say git push origin which is the name of our remote location and you will issue that command anytime you have changes you want to push up to GitHub by default we're already good because that was part of the command you can see that get push origin now I'm safe to record this video because if I screw up I can just reset my local changes and we'll be good to go so the very first thing we want to do since we are working on a python project here is activate a virtual environment so we'll say dot dot VNV slash bin slash activate or the windows equivalent which I showed you in the previous episode so now that we're in a virtual environment we can say python version instead of python3 and you can see It'll say python 3.9 so when I'm within that virtual environment which we created with python3 we don't have to say python3 anymore it also gives us access to pip directly so when we say pip dash dash version we're on 22 for python 3.9 so we no longer have to say Python 3 Dash M pip install and then the name of whatever we want to install instead we could just say pip install Django rest framework as an example so let's go ahead and install that warning you're using pip version 22.0.4 and it's suggesting I upgrade so you can say pip install dash dash upgrade pip that will get everything good to go so you might notice something interesting there is no changes in our source control here so one major difference between how react works and how Django works is that when we install something it'll automatically update our package.json when we're working in react for a Django project it doesn't automatically add everything to a package list we have to create that file manually if we want to keep an updated list the actual installed package goes inside of our virtual environment which is grayed out because it's not being checked into Source control so what we will do is say pip freeze and you'll notice that this will put out all of the different packages we have installed so we can say pip freeze and then redirect this into a file called requirements.txt so by convention this is the file name that'll keep track of what packages we've had installed and if you want to use this project later how do you do the equivalent of npm install you might be familiar with from react well you would say pip install Dash r irements.txt and that's going to go through that file and install every single one so as a friendly reminder whenever you update your packages that you've installed and need for your project you'll want to add it to the requirements.txt by issuing that freeze command again so what we'll do is we'll say git add and then git commit add requirements.txt and then get push Perfect all right we just got done with all that boring garbage now what I want to do is I want to start working with Django rest framework which is how you build a rest API inside a Django so rest apis that's what we were talking about in the previous episode it's basically just an agreed way of transferring data between applications so this is going to allow us to get data create new data update data and delete data and it's all going to be in a Json format so this is going to be very similar to working with objects in JavaScript Json is actually JavaScript object notation so it's a very easy thing to pull into our react application and I've already kind of mentally prepared you here because these are JavaScript objects will it be exactly like this maybe not but we'll be able to switch in new data fairly easily without changing our entire application so what we're going to do now is we're going to create a model in our Django application this is going to be a representation of data we're going to create a URL path so we have a location to access the this data and then we're going to create what's known as a serializer and this is going to describe how we go from database objects to Json data so lots of stuff let's just jump in and get to it so if you remember when we ran our server last time we did python manage py run server and it gives us this 18 unapplied migrations this is because we are working with a structured database by default it's sqlite with Django but easily substitutable for other relational databases such as postgres or other ones out there as well if you want to do a nosql database then you'll probably want to do some additional research on your own because this is what we're going to use for now but this is an important thing to note is that when we are using a relational database we have to use these migrations which are basically describing the changes that we need to make to the database from our code that way we don't have to work with SQL directly so that might be a lot if you're new and again we're kind of doing a back-end crash course here but basically what we're going to want to do is quit the server or you can keep it running and open a new terminal window here and we're going to say python manage.py migrate so when we create a model we will need to add that migration as well so let's go ahead and do that we'll go into our customers and we will say new file models.py and in this file we are going to describe any model that we need for our application now remember model is just another word for database table essentially you can think about it as the different entities we need to describe and it's going to look like this we're going to say from django.db import models so pretty similar to react I just flipped around whereas in react you use import whatever from whatever python you're going to do from whatever import whatever all right so hopefully you got that figured out and then we will say class customer and we'll put parentheses here a colon inside of the parentheses is where we Define inheritance so this customer is going to be a derived class from models.model and then inside of the class this is very important make sure you are indented this is required in Python so we will say name models.char field and then inside of parentheses we can give it different conditions so max length being equal to 200 for example and then we could do another one say industry is models.char field max length of say a hundred so this will describe the attributes each customer is going to have they're going to have a name and an industry so to put this inside of the database we're going to go down here and say python manage.py make migrations and then the name of our app which is this right here customers so we'll type customers no installed app with label customers a quick fixer for this is we basically have to go into our settings and say hey this project that we are working on this is really important so actually care about it and to do that you go in the installed apps and you're just going to add the name of your app which is customers kind of dumb but you just gotta do that so now when we issue that command it works and we get this new migration file which describes are changes to the database and this is something we check into Version Control so this is the migration and it describes the changes to the database and you can get a little bit more details here next up we apply this migration to actually make this change to the database so we can X out of that we don't actually have to look at that file we can just say python manage.py migrate enter and that will create the change on the database and as a quick subtle but essential advertisement we go through all of this stuff in the back end course in much more detail and I have this ebook that shows every single step and all the important commands so definitely consider checking that out you can find links in my descriptions and pin comments throughout this channel but we're going to go over everything you need in these videos but if you just need a little extra that might be helpful so let's get back to what we're doing let's make that URL path we were talking about so this is going to go in urls.py so this is similar to the routing in react which we put inside of app.js so here we're saying which paths go to which component similar thing inside of Django the difference being we're going to put the path and then follow it up with a view which I'll describe here in a sec we will say path and inside of here we can say API slash customers and then this is going to go to views Dot customers this is basically the function that's going to accept the incoming request I'll show you how to make that in a sec so name and just call it customers all right so we have little squigglies here we're going to say from customers import views so we're going to import a file from our own project so we'll go into customers right click new file views.py and from here we will say death customers in parentheses you'll say request this is going to have data that describes the requests made from the client inside of here this is where we are going to invoke our serializer which goes from database objects to Json data and return to client so this is just a comment inside of python you have to have something in your function so if you're just going to fill in a blank spot for now you can use the word pass so we're going to come back to this we need to create that serializer so go customers new file serializers.py now from within this file you'll say from rest framework this is something we actually have to add to our app so we'll go back to settings uh yeah there's so much jumping around it's crazy so we'll say rest framework someone needs to make a create Django rest framework app command so that would be really helpful if you guys want to do that back to serializers we'll say from rest framework import serializers sometimes you'll get these issues here where it doesn't recognize and what you need to do is you need to tell python of your virtual environment so you can type in here select interpreter and from here you will use this one with a star python 3.9.12 inside of the virtual environment so clicking that and that goes away and then we need to import our model so from customers import models or you can get a little bit more specific so from customers dot models import customer so that's going to import this guy right here and now we're going to say class customer serializer and this is going to inherit from serializers dot model serializer so very similar to how we created a model where we said what it's going to inherit from and we used that as the base class for a new class so this describes our data and then the serializer describes how to serialize it inside here we're going to have a nested class called meta say model is equal to customer that's the model that we want to serialize and then what fields we want on that is going to be underscore underscore all underscore underscore alternatively you can put each attribute you want to include in a list but I'm just going to include everything here okay so we have our serializer it looks good everything is going good now we just have to use the serializer in our view so hopefully we can get this right what we'll do is we will say data is equal to customer dot objects.all that is how we get all of our customer objects we will say from customers dot models import customer next up we're going to serialize all that data so we'll say serializer and assign it the value customer serializer this is going to create a new customer serializer object and we're going to pass in our data and say many is equal to True with a capital T lastly we're going to return Json response which we can import so from django.http import Json response and inside here we pass what we want to return and we're getting a problem here customer serializer is not defined we want to import that so from customers dot serializers import customer serializer return Json response here we just pass the Json data and I'll just do it as a single key value pair so we will say customers and then colon serializer dot data so we take this data variable we pass it through the serializer and then we use serializer.data to get the serialized version this is basically the Json compatible version that we're going to pass as a response so that should be everything in theory we just coded the whole thing without checking along the way so hopefully we're not too far gone from the terminal we'll say python manage.py run server heading over to localhost 8000 we get page not found 404 and this is based on the URLs we defined so let's check out our URLs real quick we'll go over to URLs and we'll see we need to pass in API customers so over to this here we'll say slash API slash customers and it worked the only problem is there's nothing in it but this is a seriously good first step congratulations especially if this was your first time using a back-end language like this if it was a little challenging you might need to go through this video a couple of times or go a little bit slower following the a Django course that I mentioned in the next episode what we're going to do is we're going to learn how to add data into our Json data there and consume it from the react front end so it's going to be pretty awesome that's when we'll be able to see these pieces come together as a friendly reminder I am checking this code up into GitHub so if you followed along and it was just a little too much then you can always go to that repo go to the commit history copy the code at whatever point you need in this series so I will make that commit now so you can see the message which is adding our first get endpoint perfect so we will commit all these and there you go [Music] welcome everybody in this episode we're going to continue our API discussion in the last two episodes we created a basic Django application and then created an API the only problem was we didn't have any data so we're going to start this video off by talking about how to put data in our database get that data to show up in our API and how to request for that data in our react application so overall it's going to be pretty cool let's get to it so this is our API so far not too many customers probably ain't making too much money from this list of customers so let's go ahead and add some customers to this list and the easiest way to do this is inside of your app right click new file and say admin dot py so this file we can describe an admin site that allows us to have crud access to the database without too much extra effort so what on Earth am I talking about well if you go to the site and you drop all this stuff after localhost and you do admin it'll bring up this login page so let's go into this page and see what's there but I already have these Auto filled values that doesn't mean I necessarily have an account though this is just saved from the previous times I've used Django so what we need to do is we need to create an account and we do that from the terminal so let's close out of this and we will say python manage.py create super user go through these prompts so we will create a username enter is fine and give it some secure password such as password this password is too common bypass yes obviously you're not going to want to do that in production but I always do that for testing that way I can always remember what my password is now let's start our server back up and go visit our login page again try to log in actually I changed the username so whatever your username is and there we go we can go into our different tables and look at the data so here's our user what we were doing with this admin.py site is configuring this page so that our new table shows up here right now we just have the default stuff that came with Django so let's talk about how we can do that we'll say from Django dot contrib import admin and then from customers or application name dot models import customer now all we have to do in here is say admin.site dot register and pass in our model customer save that going over doing a refresh and take a look at that here is our app name and we have one table in there called customers you can go in here and you can see our data we can easily add a customer in here let's pretend we have a customer Intel processors and now we have one customer object with that data now let's go back to our API so we'll say slash API slash customers and take a look we have one piece of information with an id1 name Intel industry processors looks awfully similar to the structure for our data we defined and react so we'll be able to create a pretty similar example for the customers page so let's go ahead and add a couple more customers so we'll go back to the admin site save and add another go something like Taco Bell what industry is Taco Bell and it would be restaurant industry no it can't be it's got to be something like the tacos industry alright so we'll save let's add another oh yeah click the wrong button there let's add another one under armor in the industry clothing sure okay so now at this point we should have a few more things in our API which will make it a little prettier API customers cool now let's talk about how we can use this API or consume the API from our react application the component we have that's most similar to what we're trying to achieve here is going to be the definition component because that actually makes a web request and puts the data in the page so if you need to use that as an example you can so I'm not going to copy the whole thing but let's just take a look we're going to have a use effect which makes the request to a URL we're going to assign that to some data and then we're going to Loop through that data displaying it on the page not too bad so let's start with the web request so we'll do a use effect with a fetch inside and we're going to put this inside of our customers page and we have it set up so that when somebody visits slash customers it renders that component Perfect all right so the first thing is we're going to create a use effect and that's going to need imported so we'll say import you can already tell you'll mix up syntaxes I was going to say from something import but I need to say import use effect from react cool now we have access to that so we'll say use effect and this is going to take a function which we will Define it in line here console log I just like to make sure I'm saying and test it out fetching and I will need to start my application actually once that's up we can go to the customers and we will open the console all right cool so our use effect is being executed and now what we can do is we can make a fetch so the fetch is going to look like this fetch dot then dot then inside of the first one is going to be the URL which is going to be HTTP colon slash localhost 3000 slash API slash customers if you just need a sanity check you can control or command click that and see I already screwed up because it's supposed to be 8 000. so that's why it's good to check there we go that's what we're looking for and now the next then is going to have the response as a parameter and ultimately return response.json too bad so we'll create a function here response return actually we'll just uh get rid of the curly braces and say response.json the curly braces are only required if you have multiple statements and the return is implicit if you're not using the curly braces last then is going to have data and we're going to just assign it to some state so another function here this one will probably end up being on multiple lines so we'll say data this is going to require state so we will also say use state and Define some State here const customers set customers is going to be assigned use state Perfect all right now what we do is we would just say set customers data and I'm also going to console log data all right cool let's go back to our page and check out the console all right so it will see an error here access to fetch at this URL from origin localhost 3000 has been blocked by course policy by default our backend is going to deny all requests that come from An Origin that is not explicitly allowed to do this we're going to install a package to configure course so to say that one more time this is the path that we are making a request from this is known as our origin we need to Define that as a legit origin in our back end this is the package we're going to use to do that Django cores headers so in our backend code I let's quit our server we will say pip install Django cores headers I was experimenting with this earlier so it says requirements already satisfied yours will actually install and then what we will do is say pip freeze and direct that into requirements.txt I try to remember to do that whenever I install something now there's a few steps we have to do which is add it to the installed apps and the middleware I'm going to copy this from their repo but it's not that long so if you're just watching you can type it out I'm sure so course headers being sure to add the trailing comma so we'll add that in here cores headers comma and then the section for the middleware I'm just going to copy that should be placed as high as possible so I will just put that first thing inside of the middleware section and I'm just going to format this to be consistent with the rest of them there we go lastly the only other thing we have to do is create a list of allowed Origins so I'll just Define that right below the middleware section course allowed Origins and I will make that a list and in here put HTTP colon slash slash localhost colon 3000 save restart the server run server now let's try and make that request from localhost again we're still getting that similar error we're not getting any errors on the server side so I must have missed something so I think I know the fix for this and it's stupid but it's just that we need to add a slash at the end of the URL we are making a request to and I also remembered I need to add the empty dependency array here so that it only does this once on initial load so let's check it out now and take a look we have access to our customer data right here that's pretty cool now we can display all this data on our page using map so in the return I'm going to put parentheses and we will use a fragment so just to empty lesser than greater than and we will close the fragment we can still surround if we want to title for example we could put an H1 and we'll change the text here here are our customers and then we will say customers.map surrounding this with curly braces and then this is going to take a function where each customer is assigned to the parameter variable customer we'll just make a paragraph here inside of here we will want to say something like customer dot name now keep in mind of the problem we also had with definition where it tries to do that too quickly so we used a ternary to see if that had any data in it so we'll do the same thing here so we will ask customers does it exist if so then we're going to do all this stuff otherwise we are going to do nothing so you could use an empty string or say null all right on Save now customers.map is not a function if you take a look at our data It's actually an object with an array inside of it so we basically need to jump inside of this customer's attribute taking a look at our data we want to access what's inside of here an array so to do this we could do that down here if we wanted but I think it makes more sense to say data dot customers here and then we can treat it the same down here now if we take a look at our site boom baby there we go those are our customers and that is how you make a get request to a custom backend lots of Hoops to jump through for this one but we finally got it working so thank you for following along stay tuned for the upcoming episodes because I want to continue building on this and ideally we can get full crud capability on this application the ability to create data read data which we already got up data and delete data thank you for watching be sure to subscribe and I'll see you in the next one [Music] welcome everybody this episode we are going to build a Details page this will request the details for one element from our API so let me explain and give a little visual right now we have these three customers which do in fact come from our API so id1 2 and 3. however if I want to say click one of these and bring up a new page that has everything about that customer this is where it details API and Page would come in handy this page would also be where you edit and delete any specific customer now when it comes to creating a new customer this doesn't describe any existing customer so instead it's going to be associated with the entire list so creating a new one I would have a button probably on this page versus inside of these different customers this is pretty similar to how the back end for Django is set up so if I go to the admin site from this page where it describes all the customers you can add add a new one or you can open a specific one and get the detailed information which you can edit or you can delete the customer altogether this is basic crud ability create read update delete and that's what we want to learn how to do fully in react I want to share some code with you but this is more advanced than where we are at so you don't have to understand everything here but this is going to be something along the lines of what we're doing where in this one we wanted a list of files this is where you get data and post data posting data is how you add data alternatively you can get a single file and this is where you get the single file data patch for updating the data or delete for obviously deleting the data you may also see put here usually it's actually more common than patch so it'll be split up in two different functions one plural One Singular the plural will have the get and post to get and add data the singular will have three options which is get update and delete data and then you can just case inside of here to check what method is being used so when we create a request to the backend like we're doing here by default this is going to be a get request so if you right click inspect go into Network do a quick refresh you'll find that request in here where we are requesting data from customers and taking a look at this you can see request method is get so we're going to learn to use other request methods through fetch to build full crowd capability so with all that information now in our brain let's go ahead and make a details API first because that's going to be what we build off of so we'll go into localhost 8000 customers and then we want to be able oh forgot the API API and we want to be able to grab an individual customer passing in their ID here so this is what we want to get working to do this we're going to need to modify two files first the URL paths and then we'll create an Associated view or function to accept that so comma after that path and then this one's going to be API slash customers slash in the way you parameterize is with less than greater than the type of data and then the name so int ID for example views Dot customer singular and then name same idea customer so we created that view it's going to complain there's no attribute customer on customers.views so we'll go into there and create it to fix that error so deaf customer request all right so that's how you associate those two now we just have to Define this Behavior I just put pass in there so it wouldn't error out because if you don't put anything in the function body it'll complain not really a mandatory step just wanted to make a little checkpoint so it's actually going to be pretty similar so I'm going to copy these lines here paste here and what we're going to need to do is we're going to need to change customers.objects.all to get because we don't want to get all of them we only want to get one of them and we let the database do that versus filtering through it in our backend code so then we need to specify which one we want with the primary key so this is a name parameter so you have to say PK equals to some value that is going to be ID which is going to be passed in so let's go back to the URLs real quick this value right here is going to automatically be assigned to this variable here that allows data to just be a single customer next change we're not going to need many true so you can delete that and then you can get rid of the plural here so it's just a single customer all right so there is our endpoint at this point we should be able to refresh this page and we get the single customer another quick note if you haven't figured it out already Django Pages you're going to have to refresh whereas the react will automatically refresh for you so this is a single customer now we can make a request to this endpoint substituting in some value whatever we want on the front end so those links will be one two and three in this case so let's head over to our react application and create those links so right here we have the paragraph We can replace that with an anchor tag or I'm going to use the link component from react router so this is going to be two and then we'll have to substitute some value in here for now I'll just put the pound sign which will point to the same page and then import link from react router Dom cool all right we'll save let's check it out it's uh not looking too hot so we actually need to put those on different lines so you could surround this with a div or a paragraph I guess we'll just put the paragraph back in now each one should be on their own line that looks a little bit better right now the Links don't actually go anywhere because we haven't defined the URL path so what we need to do is the link should be to slash and I think this is from the root so we'll say customers and I'm going to surround this entire thing in curly braces to evaluate a single value because then it can easily Plus in customer dot ID this value comes from the Json data and we can check our page looking at the links down in the bottom left customers one two and three you can click one and see it goes to the correct URL we just have to Define this page and that is exactly where we're going to stop this video and continue in the next one which will consume the details API and display the info on the page hopefully this video is helpful stay tuned for the next episode subscribe foreign [Music] welcome in this episode we are going to continue our discussion on the details page so we already did the API in the previous video now we're going to do the react part of this right now this is what we have and these will link to individual page that'll give more information about each one of our customers so if we click one of these right now nothing is there this really should display the data for customers number two which is this right here so to start with this we're going to create a new page for an individual customer set a new file customer.js this is going to be kind of similar to the definition page because in this one we passed in a search term in the URL and used that to get details on a specific element so we're going to follow that pattern so let's go ahead and we will say export default function customer and we will just say return and the only thing I want to return right now is let's go ahead and return a paragraph and inside of this I want to print the ID that is passed in so I reformatted the return a little bit just to put the parentheses and the fragment on the next line now I have to ask ourselves where does this ID come from is it props no it's not props it comes from just like in definition the use params hook which comes from react router Dom so let's go ahead and Implement that behavior here we will say import use params from react router Dom and then inside of our function we're going to create a variable which we will call ID and we're not going to have it quite like that we're actually going to have it inside of curly braces and set this to a call to use params like so now surrounding a variable in curly braces we'll grab the property on object so use params returns an object we only want the ID and that's how we can assign it to a variable called ID so in theory this should work but there's no way to access this right now even if we do visit a customer like this nothing happens so we need to deal with the routing so let's go back and we want to render this component when we hit the customer's path with an ID passed in so it'll look pretty similar to this just slightly different so let's go ahead and copy paste and it'll be customers slash colon ID the element is going to be customer singular so let's go ahead and import that import customer from dot slash pages slash customer fabulous there now when we visit the page in theory we should get the number displayed on the page so far so good so now we just got to take this ID and make a request to the appropriate API endpoint and we can do this just by appending the ID to the URL for the request so to do this we want it to happen immediately one time so we will use use effect be sure to check out the previous video on use effect if you are not familiar but we'll say use effect and this is going to come from react and I will Define this after any variables and we just invoke use effect this is going to take two important arguments the first being the Callback function and the next being the dependency array which I'll leave empty which will make it execute this function once on page load so just for my sanity I always like to console log it's a little Overkill but it helps you notice if anything is weird or if you're an infinite Loop or whatever it may be so we'll just say use effect here so now on page load we should get one use effect I get two because I'm in Dev mode and I have strict mode enabled so that's why you see a two here if yours is one it's no big deal so now let's invoke fetch I like to start with the basic structure so I'll say fetch dot then dot then and then fetch is going to take a URL which we will Define above so let's push this down current zero this is going to be HTTP colon slash localhost colon 8 000 you probably notice we're having some repeating information this is here as well as here so it's a good area to introduce bugs or I guess I should say bad area so we probably want to fix that at some point and put the URL in one location and just refer to that location this is fine for now um just because it's easier so we will just say localhost 8000 and we might change that to a reference later this is going to be slash API slash customers slash plus ID perfect now for then these are both going to take a function so it'll look like this same here and they will both have a parameter so this one is going to be called response and this one is going to be called Data inside of this function we will just say return response.json and then inside of here we will set state so we'll say set customer and pass in data Dot customer a couple things we need to create the state and just before we do that I want to explain we're saying data.customer because if you take a look at the responding API it says customer here so if we want to jump in and grab this object well then we will want to say Dot customer if you're working with an API that had multiple properties well then you wouldn't necessarily have to jump in like that all right so let's go ahead and create this state so this will also be from react so we'll say use State and I will Define that here so const and we'll have customer set customer and assign a use State and then down here we can conditionally render it if the customer is set so we will make a ternary and say customer with the question mark If we have a customer let's go ahead and render the customer dot ID otherwise we will just render null saving that let's take a look at the page go over here we get two and it seems to be working and what we can do now is we can put in all of the properties for the customer instead of just the customer ID so what I would probably do is make this a div and then inside of this div we can put multiple things so we will make the first one a paragraph and then we're going to take this line and paste it twice so we'll say ID name and Industry there we go save let's take a look at the page now and there we go we got two Taco Bell and the industry is tacos let's go ahead and try the other IDs just to see some options yep seems to be good overall not too bad once you've got it working you can of course remove the console logs if you have any problems with that I would likely put a return link as well to go back to the full list so we can just do that at the bottom of our return here so after the customer data we will put a link which will have a two and this will be to slash customers go back saving that let's check it out we have to import link so scroll to the Top This is in react router Dom link there we go let's try it so go back there we go so that's what I wanted to cover in this episode The Next Episode we're going to figure out what happens with 404s right now our application just breaks if you want to see that you can put in something in the URL that just doesn't make sense so for example we could go to slash Pizza so we need to make an appropriate page when something is not found so far so good stay tuned for the next episode I'll see you there peace out [Music] in this episode we're going to figure out how to make our page show up properly if something goes wrong with our fetch so the first thing we're going to worry about is 404s and then any other General errors we're also going to move the URL so that we don't have repeating values throughout our application so this video shouldn't take too long let's just get through it and then we'll move on to something new we check for a 404 in the first Vin of the fetch because response is going to have a status code that you can check for so we can say if response dot status is equal to 404 then we know the resource was not found I think you could reasonably do one of two things here so the first one would be to redirect to a 404 page the other would be to render a 404 component in this page this would be a new URL but would be fairly consistent across pages and would be really easy to do this one requires a little bit more custom coding or logic but might be a little bit more friendly because you can say something like this customer was not found or the customer with the name Taco Bell was not found so we will go with this one first and then we will try this one the first technique is going to use use navigate so that's actually in react router Dom anything with linking and navigation is react Rod or Dome so we'll say use navigate and then we will create a variable to refer to this so navigate use navigate and then we will just say navigate so it will look like this here let me put it below this comment navigate and then we can pass in a path here so we'll just say slash 404 and this path was set up inside of app.js so you can see right here we'll render the not found component now let's visit our application now we can open any of these and let's say we go to a customer that does not exist such as customers five you can see it's actually not redirecting what's going on well we're actually getting a 500 internal server error from the server you can see these requests in more detail on the network tab so our backend is actually not returning the appropriate status code let's take a quick peek at our back end so right now we have this customer.objects.get this will actually throw an exception if no data is found so what that means is we could check for that exception to show you what I mean we could say print and just so we can really easily see this I'm going to put a lot of exclamation marks because we're going to get an exception in the terminal and it can kind of fill up the screen a bit so we will go to the localhost 8000 and put in an ID that doesn't exist and it does not exist at and then this path looking in a terminal we get this exception and nowhere do we see our print statement basically we get to line 11 it doesn't work and things just don't continue that's why we're getting a server 500 instead of a 404 so there's something wrong with our server what we need to do is we need to surround this in a try so it'll look like this we'll say try if something terribly wrong happens we can catch that so we will say accept and we can check for a specific exception and it's going to be customer dot does not exist so that is how you check to see if there's any data returned if there's not we can just say raise HTTP 404 and put in a message customer does not exist this is going to need imported from django.http so we'll put that there after a comma and now when we check the back end do a quick refresh we should get a 404 instead and you can see our custom error message right there this page here you won't see this in production you'll set debug to false but for debug being true this is Handy seeing exactly what went wrong with our custom message so all we need to do now is we need to check our front end do a refresh and take a look at that it redirects to slash 404. cool let's try the other option which is to embed a 404 component in this page so in that situation we're going to use state so I'm going to copy this line here and change this to not found and set not found then all we do is instead of navigating to 404 we're just going to I'm going to get rid of this line set not found a true and then we can check for that value later on in our code so down here we can say not found if it is we will render the not found component we've created earlier otherwise nothing so now when we go to the page let's go back we'll go to customers five for example it keeps that URL and it says the page you were looking for was not found it's a pretty simple component that we have right here that's not found which we created in an earlier episode it literally just returns this paragraph so feel free to not even use this component you could just copy this text or type it out yourself and put that in here directly this would allow you to substitute things in a little bit easier or alternatively you could Define this with props and substitute in here I'm just kind of giving you guys some options so let's try here the page you were looking for was not found and let's try the customer with ID substitute ID was not found and we'll just put the ID passed in here now we'll see the customer with id5 was not found so far so good the only thing I want to do now is rearrange our URLs so that we don't have duplicate URLs throughout our application this will just help reduce bugs that way if we change where our API is located we don't have to go through a bunch of files and change it so the way you do this you could probably do it a lot of different ways I'm going to keep it pretty simple and just open a single file inside a source we can just call it something like share.js and any kind of shared values you can put in here now inside of here we can Define the URL so we will say export const URL and I'm just going to call this base URL so kind of like the start of the URL and this is going to be HTTP colon slash localhost colon 8000 slash now because we have this export we should be able to go into the customers file and import it so we'll say import and then inside of curly braces since it's not a default export we will say base URL from dot dot to go up a directory and then shared now when we're defining the URL down here we can remove this part and put that at the beginning so we'll say base 0 Plus there's a cricket in here and he's I can't find him anywhere it's driving me crazy anyways let's check this to make sure it works so it seems everything is working the same way let's try three let's go ahead and do the same for the customers page so we'll import it first import base URL from dot dot slash shared and then we remove this part of the URL and we'll just say base URL plus and you can clean this up too if you want so we'll say const URL take this line paste it here and put the URL here just for consistency sake and then I'll just remove these console logs looks good checking out the front end still seems to be working thank you for watching and stay tuned for the next episode peace out [Music] in this episode we are going to be continuing building our different API endpoints for full quad capability I'm not entirely sure how long it's going to take so we're just going to start and see how far we get in this video right now our API is working but it's pretty Bare Bones so we're going to expand on it and make it better why am I up at three in the morning making videos I don't know so if you don't have this code exactly as is and you want to follow along exactly I just did a commit called bit I swear if that Cricket doesn't stop cricketing I'm gonna punch it in its Little Cricket face anyways Ron commit basic 404 and here is the URL the first thing I wanted to try to explain is that the way we're doing this with a Json response and an HTTP 404 does work however there's a more suggested way as you build out an API so we're going to change the structure of our code a little bit here at first it's going to be a little strange and you might be like what value is this adding but as we go on you will see so the very first thing we're going to do is we're going to put an at sign API View and inside of parentheses we're going to put a list with get comma post comma and delete so this is how we Define an API that can take get post and delete requests and we're using this API decorator and this describes functionality for this function so what we want to do is we want to import this and we're going to import some other junk too so we'll say from rest framework dot decorators import API View from restframework dot response import response and from rest framework no dot import status so these three things we're going to use throughout this code so we can use response to do all of our different responses whether it's a Json response a 404 or HTML even which we're not using HTML but you get the idea the API view says which methods are allowed and the status is going to give us a bunch of options for status codes right now on the front end we built functionality to accept for a force currently it's not working because we changed our backend code and I just saved it but we've coded the functionality for a 404 but we don't have any code for General errors 500s or unauthorized errors or whatever it may be and those are different status codes that we may want to return that's what we're going to be using this status variable for so you'll see that here in a moment all right so enough of the Imports We Got The Decorator saying which methods we can use now instead of returning a Json response I just want to return a response and that actually reminds me this should be Capital sorry about that so the response is going to take the data and optionally you can pass in a status so status equal to status Dot and you can see all these different HTTP status codes that we can give back with our response this was a 200 so we would just say HTTP underscore 200 but this is also the default so it's not really necessary so I'll just go ahead and delete that but we're going to do something very similar for our other responses to try it out let's create a response here we will say return response instead of raise and inside of here we can skip the first thing which was the data and just do the status so we'll set status is equal to status dot HTTP underscore 404 saving this let's check out our back end we will visit a page that does not exist we get this weird New Look which is fine it's something Django rest framework has to make working with our API a lot easier so we'll have the ability to get and delete data and post new data and it'll give us the error message right here HTTP 404 not found another benefit of having this page that Django rest framework gives us is we don't have to use external API testing tools like Postman as much so we could try deleting any of our customers so let's go to a customer that does exist like customer three and now we can delete this customer but it's not going to work quite like you would expect so we hit delete but the data is still here and we can still visit this data without getting a 404 so just because that button appears doesn't mean that we've coded the functionality for these different buttons these are basically just the UI for the behind the scenes functionality for the delete and post methods so in our code we actually haven't done anything with those methods so if we wanted to we could for example let's try building out this delete functionality so if we get past this point we know that the customer exists so what we can do is we can check what HTTP method the client is using IF request dot method is equal to get then we're going to do what we already know which is this right here the alternative option LF request dot method is equal to delete what are we going to do this one's actually super easy we're just going to say data dot delete and return a response and this is where we can use another status code so we could say status is equal to status dot HTTP and we're just going to use 204 no content there's all kinds of different things you could do that's what I'm gonna go with now that we've had the delete functionality coded we should be able to go click this button and delete one of our customers so we'll hit delete we get a 204 no content and now when we visit the same URL we get a 404 so it appears to be working and if we had the same view for our entire customers list we could see everything so why don't we go and try and do that now we will say API View and in here we're going to allow get we're also going to allow post so post is used to add data it can also be used to edit data which will be for down here you may also see patch for this but we'll stick with post for now until we decide we might need otherwise but for now post should be fine and we will return a response instead of a Json response saving that let's take a look at our page we will go visit customers and now we see one and two let's go back into a specific customer such a customer two let's talk about this post ability down here this will be used to edit the data for a specific customer so to code that we can just check for the request method being post if actually alifrequest dot method is post what are we going to do it's going to be kind of like line 23 here where we get the customer serializer but with us updating data we're actually going to have to pass in another argument so it'll look like that serializer is customer serializer we get the data from the database this is the element we want to refer to and then the new data is going to be passed to a parameter called data and this is going to come from request.data now they could just submit any kind of garbage so we actually have to check to see if the serialization was valid so if serializer dot is valid right here and this is a function call so if the serializer is valid we will save it with serializer DOT save and that is a function call lastly we can return a response passing back the data serializer dot data and we might want to surround that in a dictionary kind of like what we did here so let's just do that we'll say customer a serializer.data there we go that'll be for consistency now the last thing is if serializer is valid as false it will go down to line 33 and we can return any error so the way you do that is return response serializer dot errors and make sure I get everything spelled right serializer dot errors now this I'm just gonna warn you okay it suggests error messages it's not error messages it's errors and then we can say status is equal to status dot http 400 bad request so something they sent us is bad if you're new to backend development there's a good chance you're watching this like um what exactly is going on just wanted to let you know that that is totally okay this is really a front-end course so I'm going over the back end material quite quickly which is exactly why I have a back-end python course which goes over this in much more slower detail as long as you have a pretty good idea of what's going on and you're able to get the code working that's great that's the start of your practice for back-end development as well so you'll get better over time and it's not like I had this all memorized I was referencing some of my other code and notes so don't expect to ever be perfect let's go ahead and try this out see if it works so we'll go over here and what you're going to do is you're going to take not the outer customer but just the object here copy it paste it and this is going to be the body of the request and inside of here you can update it with new information so for example the name could now be Chipotle which is ultimately a more Superior place to buy tacos I don't even like tacos but I love Chipotle in general so we're going to update that and now the data that's returned says Chipotle and they are in the tacos industry if you go back to all your customers that persist and there you go that's how you're going to update data now down here we also have a form this is to add new data not update data so in this situation it's going to be pretty much the same but instead you're not going to have an ID that's because you don't know what the ID is going to be that's what the database does it generates the ID for you so let's talk about how we can Implement that behavior because right now it's not going to work if we go down here and Define some object like so let's come up with a new name Burger King and they are in the burger industry I don't even know if you'd consider that like an industry but doing this it's not going to give us what we expect nothing happens so this behavior is going to be defined in this function because adding a new element refers to the entire list we're adding an element to this list we're not editing a single element which would be customer singular so let's define it up here and it's going to be pretty similar where we can check what their method is so if you want to give it a shot you can pause the video and try it pretty much what we'll do is we'll just surround what we have and if request dot method is equal to get so if it is we will get the data serialize and return however if the request not method is equal to post then we're going to do something a little different and this line is going to be a lot more similar to what we have down here where we are getting the data from the request the only difference is we're not going to refer to something that already exists in the database so I'm going to copy this line since it's going to be really similar we're just going to make one small change so paste and I'm going to remove this first data which is the data from the database so it's a little confusing with the naming but once you kind of Follow That pattern you will start to understand so there's kind of three ways we've done this so far the First with just data passed in directly this is getting data from the information the second where we pass data indirectly and to a name parameter the name parameter data is expecting the request data what's being updated and then finally the third version where we drop what we want from the database and we're just giving new data so yeah maybe a bad choice of naming with naming this variable data if you wanted you could call it like DB data or something if that helps next up we just check to see if the serializer is valid so serializer dot is valid if it is we will say serializer.save and then we'll return a response the response is going to contain the new data serializer dot data similarly we're going to surround this in the dictionary with the key called customer so customer and next thing is going to be the status so the status will be status dot there's one for created which is nice 201 created now if serializer is not valid it will continue down to line 20 and we can return response pass in any serializer dot errors and a new status which will be status dot HTTP 400. so something they sent us is incorrect so very very similar to updating data the only real difference is not grabbing something in the database already which is why this is a little bit different so let's test that out we'll go down here put a new object and this is going to have the tab doesn't work which is annoying name Burger King industry burgers let's try this hit post and it created a new customer with the id4 Burger King burgers awesome now when we go back to all of our customers we should see that in our list ID3 has been skipped because that referred to a previous one we deleted so at this point you have all the essential API endpoints for full crud create read update and delete in the next episode we're going to start working on the front end this was kind of like a prerequisite to that so I know it was a lot and especially a little bit different than what this course is about which is react but this is kind of an essential thing to understand and the reality is I'm trying to bring my content more to like full stack development versus just an individual technology where you learn everything in isolation so hopefully you guys like that and it helps give some more context of how things might actually be used thank you so much for watching and sticking through this really long episode and we'll see you in the next one please be sure to subscribe peace out [Music] hey everybody welcome to this section where we're going to start creating the front end to match with our back end API endpoints so we're going to start with deleting customers from our page so we're just going to create a delete button on an individual customer's page and when you click that it'll redirect back to the list of customers and it will no longer contain that customer we just deleted and all this is going to happen on the back end too so this isn't just some front-end magic with mock data the data will actually be deleted from the database before it navigates back to the original page in the upcoming videos we're also going to worry about updating data and adding new data but we're just going to take it one step at a time and I think delete is going to be the easiest transition into the more complex stuff like updating and adding new taking a look at what we have so far we can imagine we're some tech company and we have a bunch of customers such as these ones here we want to be able to go in and delete a specific customer by hitting a button that says delete and I just wanted to take a quick aside as the list here that is defined here is incorrect and you'll see in the console we'll get problem each child on the list should have a unique key prop so there's two problems here one I put the the unordered list inside of the return for the map which is a big Noob mistake so we want to actually put that outside and that's because we only want one unordered list each element inside is just a list item and that's what's going to have a key prop what's the key going to be well each customer has a unique ID so that should fix the problem and now when we do a refresh for one these don't look nearly as spaced out and we don't get a problem in the console and we will create a button here this button will say delete and we're going to have an on click Handler and I'm going to define a function in here now so far we have only done these Arrow functions just as an example I want to actually put a function name here so we will say delete customer you're just going to put the name you're not going to use parentheses and you will Define that up here so I'll just put it after the use effect we'll say function delete customer and in here I'm just going to console log deleting all right so that looks good and then I will just create a line break here because I think these will be on the same line all right so this is what we have we deleted this customer so we'll go to one that exists there's this button delete it doesn't really look like a button but again remember we're gonna do our styling later when we click the button it shows deleting in the console I like to have the function defined in the location that it's going to be used another reason why you might want to use a name versus an inline function is if you have to invoke the same function for multiple buttons right now we're defining it just for this button but let's say you had two buttons that did the same thing well then to note repeat code you could just refer to a different function outside of the the event handler now what we need to do is we need to say fetch and the fetch is going to look pretty similar but is going to be a few differences the first we're only going to need one dot then and I'll explain why here in a minute so here we're going to put the URL so let's define that up above const URL it's going to come from the base URL Plus customers forgot the API sorry API customers slash and then plus the ID we definitely need to have the ID because we need to know which item we are deleting this URL is going to be passed into fetch here but that's not the only thing we're going to have to pass in another object with the method and this is important we want this to say delete that is how we Define what method we are using with fetch inside of then we're going to have our function call so this will have the response and inside of here we are going to check if the response is okay but we're going to invert it so if it's not okay then what we're going to do is we are going to throw a new error with the message something went wrong and for that we're going to need a catch so catch is going to show up down here and all we're going to do right now is just console log the error pretty simple so the other thing we would normally do is after the if we would say return response dot Json and then we would have a DOT then with the arrow function and inside of here we would have data but if you remember the way we defined our backend code is that on a delete we are returning no content so there's not going to be a Json body in the network request so this isn't really going to work we don't need that anymore and as a result we're not going to need a return response.json instead we're just going to assume things went well as response.okay assumes a status code in the 200s so if we get to this point we should have successfully deleted the content so what we will do is we will navigate and pass in slash customers so as a reminder this navigate is a hook right here use navigate and that allows us to force a redirect back to the main list and we can get rid of that comment should do the trick but let's just try it out we have a bunch of items in the list so if we need to try a couple of more times we should be good so let's just go into any of these such as meta and we will delete and it's gone IBM we will delete Twitter we will delete so that's how you make a delete button now one other thing to note that is optional but is usually recommended is having a content type with the request so if we take a look at our Network and we go to one of these deletions the headers here for the request we want to add in here that we are making a Json request obviously our application still works without that but this is a good practice for General API consumption so what we do is we add another object in here and this has the key headers and inside of here we will Define the first header which is content type and we're going to need to surround this in quotes there we go and the value should be application slash Json save let's try this out let's go into one of these and let's make sure we're watching the network down here we hit delete we get a new delete here scrolling down to the request headers we have content type application Json so that is how you define the content type in your fetch request another thing you can do is include a body which we will be talking about in the upcoming episodes thank you so much for watching at this point you now know how to delete data stay tuned for the upcoming episodes for the other request methods see you then what's going on everybody this episode we're going to learn how to do a post request we're basically going to give the users the ability to add a new customer to the list this is going to be with a modal that pops up you can type in the data hit add if it's able to add it to the database it'll close and it'll be in the main list so let's see what we got so far right now we just have this list with two elements and we basically want to add a plus employee but for customers instead so it'll be like new employee so we're going to be copying some of that code and I literally like 10 videos in this customer section I forgot to put in this I didn't even realize that so I probably want to fix that real quick but it's not the end of the world here are our customers so what we'll do is we will take this ad employee and we're going to duplicate it so we'll say copy and then we will paste it let's give it a rename and this is going to be add customer we're going to make some minor changes we'll change the name to add customer and I have grown to like putting the export default right here so it just saves us from having to type out the name twice so I'll delete that perfect let's go ahead and add this add customer to our customers list at the bottom so after the unordered list we will say add customer and import it for us the import will look like this right here cool now let's check out our site so far it's looking pretty sweet if you ask me remember not to worry too much about the styling you know this button's over here these are over here by the end we want it to have it a little bit more pretty maybe closer to something like this but just deal with what we have for this moment now we just need to update it and make it say add customer versus employee so let's go change the text go to add customer and anywhere we see employee we will change it to customer at customer and down here we'll say add customer as well for the title we will change some of the form data so we will start with the first one which is the name we will just say customer name next up we have the role this is going to be industry for this one I will change the label as well to Industry and change the ID to Industry great and we're not going to need the final one which was the image for the employee we're not using images for the customers so we can just delete this div here great all right that should be a little bit better so add customer customer name industry let's change these default values so we'll scroll up a little bit placeholder let's go with Computing and then for the next one let's go with I don't know just Google's fine so this is what it'll look like now I'm going to get rid of this customer here I don't like that it's on two lines so we'll just change this to name great this is what it looks like now so the way we're going to have the ability to add a customer that behavior is going to be defined in the parent component if you remember when we are working with employees we defined an ad employee function inside of the parent and we pass that function down to the add employee modal so it looked a little something like this on form submission we invoked props.new employee well now we're going to invoke props.new customer and we're going to pass in the name and the role no longer the image we don't need the image at all so let's go ahead and delete any reference to image and these name and role will update role to Industry and if you don't have this code or you're just getting lost in these changes you'll be able to get it from GitHub right after this video or actually probably by now it's up there so set industry and that will be changed down here on the set here too as well so set industry and we also need to find any other reference to set role such as in the inputs we will change those to Industry okay so now we just did some basic renaming all we need to do now is to find that function that we're invoking which is called props.new customer that's going to come from customers so let's go ahead and first pass it to the ad customer so we'll say new customer is equal to new customer so we're going to Define that function and just make sure all the names line up correctly looks good and right above this return we'll say function new customer and inside of here let's just console log adding customer just to make sure everything is connected up together we will go over to the all right we already have a mistake so we have a reference to roll in the form so we'll change that to your industry we have one other reference to role in the input which will also be set to Industry okay I think that got rid of all old references I wasn't aware how much changing and updating we're gonna have to do so I apologize for that add customer and let's hit the add button but first let's get the console open and it says adding customer and it closes so now we just need to build the functionality to actually add that customer to the list and only close the modal if it was successful that might take some coordinating with the parent since that's going to be where the function is executed and the fetch results are going to be able to be seen so let's go ahead and jump into customers and we'll start working on this new customer here so we will say fetch dot then dot then pretty similar pattern to what we've always done catch and then we will Define the URL right here which is going to be base URL plus API slash customers that's the URL going to be used inside of fetch we're going to also need to pass in the additional object which has additional information such as the method which is going to be post the headers which is going to be an object itself inside of this object we are going to have the content type this is going to be application slash Json and we can also have the body and this will just be a call to json.stringify passing in data so where's this data going to come from well we're going to be passing in data that was typed in over an ad customer so let's find that function call we pass in the name in the industry so what we can do is we can Define two parameters here name industry and in here we can define an object where the name comes from the name parameter and the industry comes from the industry parameter then we'll just pass that object to Json stringify which will make it a valid body for a fetch that should be the appropriate structure for this first section of fetch now let's move on to the then here this is going to have the response and like usual we will say if response is not okay we will throw a new error and this will say something went wrong after this well we would just return the Json unlike delete this will actually return Json which is the element itself so if you look back at our post for the main customers list we will return the customer data here so if we want we can say return response.json which gives us a promise so we then have another then pass in data for the parameter here and the Json data will be assigned to the data variable inside of here we will assume the ad was successful hide the modal and make sure the list is updated appropriately if you have no need for this data like if you don't plan on doing anything with it you could do that just in the first then as well lastly we will just do the catch real quick so we'll say e console log e perfect save do a little bit of reformatting here obviously we haven't built this functionality yet but I just want to see if our post will actually work so what I want to do is first make sure all of these values are working forgot to say cons here deadline 24 Json should be capitalized my bad all right that should be everything wrong with it let's give it a shot say slack industry is communication hit add all right so the post itself did not work so let's first fix that so let's take a look at this the payload we did include the name and the industry over on the server we should be able to see a little bit more information and this is literally just that stupid problem you call this URL via post but the URL doesn't end in a slash and you have a pen slash set so you could fix a pen slash inside to false or you could just add the forward slash so let's go ahead and just change the url because that's going to be the easiest fix so this is API customers let's try this again so we'll add a customer slack communication we'll hit add and it looks like a size 201 created now we haven't updated the list functionality to show that but we can do a refresh and we see it on our list what this means is that our front end needs a little bit more polish but the functionality communicating the back end and adding that data to the database is working so that's a great first step now we have to control when the modal shows up and actually making the list update appropriately so definitely stay tuned for the next video that's where we're going to talk about how to do that and I want to do in this video but it was a little bit more complicated than I expected and I don't want this video to be like forever long so we'll just do that in the next video stay tuned [Music] foreign how to properly open and close our modal controlling all of that from our parent component right now it's all being controlled within the modal component itself which makes it a little bit complicated to control so instead we're going to create state in the parent and pass the value down to the child the other thing we're going to do is we're going to automatically update our list of customers whenever we add a new customer and it's been inserted into the database we confirmed that the backend was working in the previous video now we just need to do that front end polish to make the experience good and that way we don't require a refresh to see that new data so let's jump in there's probably a lot of different ways you could do this I'll show you what I thought of so if you want to give it a shot yourself feel free to pause the video now and go for it alright and we are back like I assumed you probably didn't get it figured out so you can follow along and we'll see what we can do so right now we are in the add customer component this is the modal and all the ability to show and hide the component are within this component here so we start with showing it set to false and this handle show will set show to true and this handle close will set show to false and you can see that sprinkled throughout this code especially also at the bottom with the close buttons so what I'm going to do instead is I'm going to Define this show state in the parent and the customer here so let's go ahead and create some state this is going to be called show and set show and we can pass this to the child component so down here we have a ad customer component we could say show and pass in the show State now inside add customer we could read that value if we wanted so for example inside a set show we could read this from props dot show and let's say in theory just to test this out we had this value set to true so we defaulted to true and this situation it should be open by default so visiting the web page and you can see it's open and on refresh it opens automatically so that's how we can have the thing be open by default if we wanted but that's a little strange I'm not going to actually default it to true so or just default it to false just wanted to confirm that it was working we want the ability to close the component from the parent because what we want to do is we want to have inside of this then hide the modal so let's head into the add customer modal and let's change these references so that show is now pointing to the state props.show this will tie whether the model is displayed to the props value but currently the different buttons we have are changing the internal state so it's going to be a little bit wonky and not work the way we would expect so what I'll do for now is for on click we will read a function from the parent props toggle show and let's define that inside of the parent so we'll scroll up here and I'm going to do this right after the state definition so we'll say function toggle show and whatever the value of show is we are going to invert it so we will say set show and then we can pass in the opposite of whatever show is and now let's pass that in as a prop as well so toggle show is toggle shell and now this button should invoke toggle show and that changes the state of show which the modal is tied to so we should in theory still be able to open the modal so we click the button and it pops up but now that functionality is not defined in this child component rather it's in the parent component where we list all the customers we can do something very similar for these other buttons so down here on the footer to close out of it with the close button we will invoke toggle show again this comes from props my bad so Props dot toggle show and the submit button well this one's going to be a little bit different because we don't want to close out of it as soon as you hit the add button we only want to close out of it if the ad was successful so what I'm going to do is I'm just going to remove this on click all together so right now here's how it works let's do a quick refresh we click add closing out of it closes it we hit add add does nothing we are still getting a network request when we hit add and that works similarly how we passed in this new customer function to the component and that fetch is defined here so all we really need to do to hide the modal is to invoke toggle show and that should close the modal so we hit add now it's not working still because we haven't actually put in any data so what we need to do is go through a test the industries test now we hit add the model goes away and you'll have to do a refresh to have that show up on the page I was testing it earlier so that's what this is we should be able to delete and take a look at that so that is how you control the display of a modal from the parent State up next we just want to have it so that when we do add a customer it automatically Updates this list instead of requiring a page refresh if you remember from a while ago we did something pretty similar inside of the employees if you've been following along if not that's okay we're going to go through it again for the customers but here is a new employee function it creates a new employee object and then adds it to the employees list and it does it through set employees which is why we have that kind of funky syntax you can't just push it onto the employees array let's see if we can do something similar with the customers right now we have assumed the ad was successful because we made it to this then block we've hid the modal now we just have to make sure the list is updated appropriately lucky for us if we console log data and take a look let's go ahead and add a customer test to and test when we hit add the data we get back is a customer and it has ID name and Industry so all we need to do is we need to jump into this customer property which will give us that object we can use in a very similar way to how we have it to find in employees where we created this object we don't even have to do that part so we pretty much just have to do this line here so we will say set customers and we're going to pass in a new array taking all the existing customers but also an additional customer which is going to be data Dot customer data.customer is how we jump into this object versus the object including the customer property so basically right now if you grab an individual customer this is the structure you would get you don't want to pass in this whole object you just want this object here all right so let's try this out make sure it works we will go back to our page we will add a customer test three testing add and it automatically shows up on the page so far I'm liking this functionality it works well it looks nice and you can go into any of these and easily delete them so we can easily work with our database quite nice so far so good we can now delete a customer we just need to build one more thing and that is the ability to edit a customer so let's take a look at the backend code to see how much coverage we have of the different API endpoints within the customers we have the ability to get all of the customers we have the ability to post a new customer we have the ability to get an individual customer right here and we have the ability to delete an individual customer now we just need the ability to update a customer so that is where we are going to pick up in the next episode this one's hopefully going to be pretty cool stay tuned be sure to subscribe and I'll see you then hey everybody Welcome in this video we're going to try and make a really cool way to edit data basically we'll have the data defaults in a form and if you go in and edit any of the data it'll acknowledge that change and ask if you want to cancel or save to do this we basically need to take a snapshot of the current data what comes from the database and then have state for any of the updated data when the person saves we will replace the old data and it'll go back to how it started without the save and cancel option so it's a little complicated to visualize with just this description so we're just going to build and see what we get and I think by the end of this video it's going to be pretty cool so we're going to be working inside of the customer component for this video and you can see here this is where we display the customer data and let's get an example open that we can look at we go through displaying each of the things the customer has what I want to do is I want to have these be inputs with these values filled into the inputs so taking a look at our code we currently have these each in a paragraph So let's go ahead and replace these with input so input type is going to be text and then value is going to be the customer ID so it's going to look a lot like this and this will be self-closing so there we go and we're going to have pretty much the same thing twice more so I'm just going to do copy paste and get rid of customer name in industry putting them here customer.name and customer dot industry so that is how we can get them in inputs and it's going oh it's hideous man I I imagine this is what you look like when you wake up in the morning oh that was terribly mean I don't know if I should put that in there but like it's the truth so let's make this look just a little bit better we're going to do all the styling at the end but what we can do is we can add a class real quickly this is a great opportunity for me to try out the multi-line editing with Visual Studio code so command option down down I think that's going to be Ctrl alt plus down on Windows and from here we can say class is equal to and I'm just going to say m-2 which comes from Tailwind so if you're just jumping in the middle this class ain't gonna do nothing but if you have Tailwind class m.2 or m-2 is going to space these out a little bit and what's the secret to get them on a next line I think we could say block for now let's see if that did it yep there we go and now my multi-line thing messed it up so let's undo for a second and lastly I'm going to add a padding of two so Ah that's ugly we want that to be uh padding X of 2. all right there we go that looks a little bit better so now what we can do is we can go in and edit these values but we want to keep track of the previous values and the new values so we're going to have some interesting setup in state right now we have a customer what I want to do is I want to create a new state which is going to be let's call it temp customer so this is just the temporary data we're typing in and this will be set temp customer and then for you state we'll just keep this as the default because we're actually going to get these values during the request at the same time when we set customer we can also say set temp customer so now we basically have a copy of the data in two different State variables so what we can do is we can change this temp customer and then when we save just put that back into customer or something like that we'll see how it goes all right so how are we going to do this first thing I want to change these values to Temp customer temp customer and this is going to allow us to change the temporary data so let's save that take a look temp oh geesh all right there we go now you're not going to be able to go in here and edit these because we don't have an on change property on our input so you can see a warning about that you provided a value prop to a form field without on change this will render a read-only field so what we will do is we will create an on change property so we're not going to do it for this one because I don't want to be able to change the ID so let's just go ahead and create one here on change and this is going to take a function so I'm going to Define that inline here e being the event and what we're going to do is we're just going to update the temporary state so we will say set temp customer and the way we're going to Define this new customer is we're going to first take all of the properties from the existing temporary customer so we'll say temp customer and we're going to replace the name property with e dot Target dot value which is what's being typed in to the input so we'll save let's just try that out see if we get anything wonky I'm going to open the console as well all right so we should be able to change this value and so far that looks great when you're doing more complex State changes what you could do just as a way to kind of check yourself is you can have a use effect and have this execute on any state change oh sorry I said state so I typed State use effect and this will take a function and we're not going to pass an empty dependency array we're just going to leave that out and inside of here we can just console log kind of a snapshot of the state so first we will do the customer and then next we will do the temp customer all right so let's save that and see if this gives us anything useful so as we update one of these values we can see all of the state being displayed and you can see the temp customer data being updated and the original customer data not being updated this can help you stay sane just to make sure everything is going the way you expect let's do something similar for the other input so it's going to be fairly similar so I'm going to copy this line here and paste it here only thing we're going to do is we're going to change this here to industry I think that should be it so now we can go in here and we can change the industry as well so far so good and since the ID is not going to be editable anyway so let's just not make it an input I probably should have done that from the beginning but uh can't go back now so we will just change this to a paragraph but I want to keep all the other stuff so we're going to keep the class so it should look something like this minus the value equals let's take a look it looks pretty good if you want you could do like ID whatever you want that's going to give you that or you could just hide it of course the ID is not really an essential component to this application so if you just get rid of it that works too so what we need to do is we need to have a save and cancel button pop up when someone changes these values so there's a few different ways of doing this you could just create a state variable that's like changed and set that to true when you enter these on change event handlers that's probably the easiest way to do this so we're going to start with that and we might finish with that as well we'll see how it goes I'm kind of going as I feel here so we'll just try it out changed and set changed and use state so again we will actually let's console log that as well so console.log changed let's go ahead and set that inside of on change so set changed to True same four right here set change to True let's go ahead and try that out we will type in something here and you can see it goes from undefined to true we could default that to false it doesn't really matter though so if we want that to be false we will put false in there it's probably just better practice that way if you explicitly check if it's false being equal to false then you're not going to get any weird Behavior now what we can do is we can conditionally render something if changed is true so we'll ask is changed true if it is show a cancel and save button so within this customer ternary because we only want it to display if there is a customer we can place this right before the final div and we will say curly braces changed if so then we can return a paragraph for now just saying changed otherwise null so that's how we can get a visual difference on the page so I change this it says changed now a very important thing to note is that when we change that value the state for change is set to true however if we change the value back to what it originally was it's still considered change this Behavior might be fine if you don't want to worry about it because it does get a little bit complex basically you will need to check the temporary values and compare them against the actual values every time you change to see if they are the same and if they are you can set changed to false so in that situation you would change this back to Computing and on that change you would compare the name to see if it's the same as the original value and you would compare the industry to see if it's the same as the original value and if it is then you could set change to false we might look at that later but for now I just wanted to finish the buttons because I think that's a higher priority so let's go ahead and create our buttons here where we have a paragraph we can and create a button and this is going to be save and we also have a button to cancel which one comes first that's totally up to you I'm going to put the cancel one on the left and now we will need to surround this all in a fragment place that at the beginning and at the end there we go so now we should have cancel and save and these should not show up on initial load until you change something and then you can have the option to save the cancel button is going to be the easiest so let's deal with that first we will say on click and the only thing you have to do here is reset the temporary state to be the same as the original state and inside of here the way we're going to do that is we're going to say set temp customer inside of here we're going to pass all of the original properties from the customer save let's try this out so do a quick refresh change Sony hit cancel and it goes back to Sony at that point we can set change to false so set changed to false so that's it for the cancel button fairly easy now let's move on to the save button this one is going to be a little bit different because this is where we're actually going to need to make a request to the back end to update that data so because fetch requests are usually pretty large I like to use them in external functions so I will say on click and inside of here I'm only going to put the function name which is update customer and I'll Define that what is this I don't know what that came from but whatever we're going to Define this after the initial functions so we'll say function update customer we will Define a URL which is going to be base URL plus API slash customers slash plus the ID for the customer we are working with and that's going to be passed into fetch we'll have a DOT then dot then then and a DOT catch this is going to be a post request so we need to pass in that additional object here and say method is post the headers is going to be an object and inside of this object we are going to have the content type which is going to be application slash Json and then lastly we are going to have the body which will be json.stringify passing in our updated customer I think this should work inside of the then we'll have the function and this is going to have the response return response.json and Dot then inline function here and it's going to have data a little console log the data which should be the updated object from the database let's just try this see how wildly off we are updated customer is not defined on line 44 sorry this should be temp customer okay so let's refresh say Sony we'll hit save and now do a refresh and take a look at that it stays the same so the change is being made to the database successfully now we just need to update the UI accordingly so on a successful response we can say set changed to false that should get rid of the buttons so now when we change the data we can hit save it saves and the buttons go away so there you have it the functionality is all there let's say in theory our URL was wrong let's just mess it up here it should be the case that we change the data we hit save the request fails and these buttons don't go away until you get a correct Network request you're not going to be able to get rid of these buttons unless you hit cancel and take it back to what it originally was so I want to try something first I'm going to change back our API URL and what I want to do is I want to add a bunch of characters to these inputs hit save taking a look at our original customer and our temp customer we can now change one of these values hit cancel and it all goes back to the beginning like what in the world well this is the important part if we want this page to be functional multiple times we need to make sure that the the updated temp customer is copied over to the original customer data when the data is saved in the database so this data that we're getting as a response this should now be the new original customer data so it's going to be very similar to what we did up here set customer to data Dot customer and the temp should already be up to date so set customer data Dot customer let's try this concept now we'll just start fresh refresh all right so I'm going to add a bunch of characters here and add a bunch of characters here we will save now let's change one of these hit cancel and it still looks good so as I'm changing this we should just get predictable functionality so far everything seems like it's working yeah I like the way this is working I think I've covered most of the different possibilities Yep looks good at this point I would probably comment out these console logs just to not be super obnoxious and then I would style this make it look a little bit better and of course you could go back to the thing I was saying about comparing the values to see if you change the data and then change it back to what it originally was maybe that's what we'll cover in the next episode stay tuned to find out welcome back everyone this episode we are going to be continuing or building of our form and we want it so that when we change data and then change it back to what it originally was the application is smart enough to know that it hasn't changed so this is what we got right now and if we change one of these values well first off these buttons look like trash so we're going to give those a little space today and if we change this back to what it originally was it was still asking us to save the data which is just a weird request it does work but it's a wasted API call and it could be confusing to the user because they might think that the data has been changed I personally would consider this feature not necessary this is more of like icing on the cake a little bit Improvement on the user experience and also it allows me to introduce some interesting Concepts when it comes to comparing objects so here's the challenge what we want to do is we want to keep the original data which we already have set up and then compare the new data to what it originally was if they're the same well then we don't need to show these cans on Save buttons but we have to check that across both of the properties so that way both of these are being considered when the data is being compared so because of that I don't really think it's smart to keep it inside of the actual inputs we don't want to have an inline function like we have here we basically want to have an external function that we can call from both of these inputs to compare all of the data because if we just compared the name for example in isolation and it was like oh it's the same we can hide these buttons but the industry was different than it originally was we'll likely introduce bugs in our software so what we want to do is we want to just invoke a function inside of here since we already have on change we can just call it here normally you could just pass the name of the function to on change but we already have a function defined here so let's just say compare customers and we're going to invoke it using parentheses same thing down here compare customers and now we can Define the logic for this function in one location and share across these two inputs and the function will be invoked anytime data is changed for either of these so I'm going to Define this up here we can just Define it really anywhere it doesn't matter I don't know here looks great so we'll say function compare customers and inside of here we basically want to decide if these two customers are equal and what two customers am I talking about well specifically the original Data customer which is called customer and then the temporary Data customer these are objects but it's not as easy as just comparing them as customer being equal to Temp customer unfortunately that's not the case because when you do this you're checking for equality of identity are these the same exact object in memory and they're not so this is not going to work this isn't going to check if their attributes are equal so there's various ways of doing this and you can research other ones and there's also different packages you can use for simple object comparison our object is pretty simple so we're going to brute force it just checking the name and the industry however if you had a really complex object or if you ended up adding attributes in here you would need to remember to update this function so so you kind of have some balance you have to think about here do you want to go find a more complex way of comparing object attributes possibly using external libraries or do you want to have this function that you now need to maintain make sure you're comparing all of the different attributes or properties on these objects if that doesn't really make any sense because you aren't familiar with how this is done that's fine let's just go through the example and see what we can do so what we're going to do is we're going to create a Boolean flag that assumes they are equal we'll check the properties if any of them don't match we will flip that flag if we manage to get to the end of the function and the flag is still set to equal that means the data is the same and we can hide the cancel and save buttons inside of here we will start with the flag which we will just call equal and we'll start with this being assigned the value true now we can just check the different properties so if customer.name is not equal to Temp customer dot name then we will set equal to false same thing if customer dot industry is not equal to Temp customer dot industry then equal is going to be assigned false now after we've gone through each of those properties we can check if they're equal and that's Boolean so you don't need to compare it to anything now we can just hide the buttons and the way we have that figured out is we have this changed state which will conditionally show those buttons down here we did this in an earlier episode so all we can do is say set changed and pass in false so that should mean that they are the same and those buttons will go away so this is pretty close but it's not perfect and I'll show you why if we go to the site let's do a quick refresh and we change it oh no nothing happens those buttons don't show up until the second change not the first change and this was bad design on my part but I decided to go with this because you could run into this so basically we are executing compare customers right after we set the state well if you remember I have said that setting state is asynchronous so we can't be guaranteed that the state is up to date by line 86. same thing down here for a line 99. so what's happening is we initiate that first set State when we change the data and then we immediately compare and when we compare that state change hasn't been propagated yet so we're comparing the initial values of customer and temp customer which are the same so we're setting change to false if you wanted to visualize this you can just console log customer and temp customer and on first change here they are the same and then on second change you're seeing the first change data so what is the solution to this the way we have a setup is kind of a logical way of setting it up and that was my first idea but whenever you have some function that is dependent on state being the most up to date that is when you want to use use effect and you can make it depend on just the state that you're interested in watching so use effect is guaranteed to execute after the state has been updated so what we'll do is we'll just take this function we've created and move it into a use effect function we already have this basic one we used earlier just to keep track of all of our state so what I'll do is I'll just replace all of this I'll take all this inside of our function cut it and take it up and put it inside of our use effect now what we can do is we can remove this function and remove the call to that function and the use effect is going to execute automatically so we're getting closer we got one more problem I'll show you if we do a refresh uncut type error cannot read properties of undefined so the problem is it's not getting the initial values of Customer because it's also coming from a use effect so one simple fix for this is to just say if not customer return same thing for the next one if not customer return now in theory that initial load is going to be skipped and it won't execute again until we have a state change so we can say Sony the buttons pop up we change it back and the buttons go away seems to be working perfect and you can of course get rid of these console logs once you're confident in the functionality so we will go get rid of those and you may notice if you're not familiar we have a single line if here whenever you have just one statement in an if you don't have to put it inside of its own curly braces so you can just put it on the same line like this here so this is going to make our function a lot cleaner there we go we can just kind of break this up into different sections all right cool last thing I want to do real quick is just make the buttons a little bit more spacious this is a really easy fix inside of our code where we have our two buttons we're just going to add a real quick class name and I'm going to set this to margin two same for this one so class name is margin two now whenever we get those buttons they're just a little bit more spaced out and it's a little cleaner that's all I got in this episode hopefully this was fun just kind of looking at some different options I think this is one of the episodes where I could have planned it out and just showed you the exact code to use but I decided let's just build this up from the beginning what you might run into and just show you how I thought through that so hopefully that was helpful and it wasn't too confusing kind of jumping around the way we did please stay tuned for the next episode we're going to continue building on this application peace out hey everybody in this episode we're going to focus on user experience there's a few things wonky with our site that I'm going to show you these are things I either missed or never thought of and really nothing is displayed to the user when something's wrong so sometimes they might be left wondering what's wrong they don't know what to do so specifically if you go ahead and delete everything hit save well uh where'd the form go what happened and you know know it seems to have done something um this field may not be blank so that's a useful error wouldn't it be nice if that showed up on the page and the form didn't just disappear another weird thing is if you go to one that doesn't exist the delete button still exists well what are we deleting exactly and why is it not doing anything these are the kinds of things we're going to fix and then maybe we can get some of these errors to show up on the page so let's first talk about getting rid of this delete button on a 404 so here we are at the button and it's not being conditionally displayed like we have other things up here only showing up if change is true and then other stuff only displaying if the customer is true or not found is true so we need to do that and we could probably just put it inside of this only display if the customer is true or that the customer exists so what we can do is we can follow this down and see where that ternary ends and what we can do is we can just take these two lines cut them and put them after the button and this is why having an extension like prettier comes in handy because this is going to reformat everything nice and pretty for us now checking out our site it doesn't show up on 120 ID let's try 12 again or whatever ID you're working with delete button is still working so that was the first problem now let's deal with the problem of the form randomly disappearing so if I hit save the form disappears well what happens when we click save so if we find save on click it goes to update customer and inside of here we are making a request and the problem it's getting down to this section here and it is setting the customer to data Dot customer well the problem is the request to the back end is not being completed properly so we're not getting a valid customer and then later on in our code when we condition for the customer this is not evaluating to True thus it's not rendering the inputs or the button which is why there's no delete here or save or cancel here either so what we need to do is we need to check for a bad request and update accordingly so let's go back to that function and what I will usually do is just say if response dot ok is false with the exclamation mark there I will throw a fit and we'll just put in here something went wrong and what we can do is we can also console log the response just to see and if you want to visualize that a little bit better in the terminal you can just put a string here so response comma response if we delete this information hit save this is the response nowhere throwing the error so we just need to catch the air so down in the catch we will Define a function and create a parameter e for the error console log e is e and now let's try this again so I'm going to delete that hit save and we see our error something went wrong so now that save button doesn't go away and we have the opportunity to put a new value in here and hitting save what we can do is conditionally display the error on the page so let's go ahead and set an error here we will just say set error and pass in e now you want to make sure e is in fact a string which I'll I will do that in a second but let's first Define this state variable const error and set error you state and we will leave that to no default value so now we'll look back and let's try this again real quick save okay so we have that error in our state what we can do is we can display it down here so let's go down at the end of customer after our button and we will place this right here we'll check for error if there is an error we will display inside of a paragraph otherwise we will not display it so we'll say no so let's take a look we're getting some issues yep objects are not valid as a react child so the error is not a string so the way we get the the message from the error I think is e Dot message and that should get the string error so now let's go ahead and try deleting this value hitting save and it says something went wrong that's awesome the only thing we need to do now is we need to have it go away when it does correctly save so at the end of our save function we will find that so update customer if something does work then we will say set error and we can just say undefined and now let's go ahead and just try this out again so let's save something went wrong updated save and it goes away same thing if we try it again without a refresh it seems to be working alrighty now you do have the opportunity to be more specific with your error right now we have a general catch all for all responses that are not in the 200 to 299 range you get just the same check for a specific error code as I believe we did up here if respawns.status is 404 you could set a different error so just do that for any of the appropriate status codes based on what your backend API is capable of returning let's go through another scenario where we might not be able to connect to the back end or something goes wrong so heading over to our backend code and we are trying to get a specific customer let's just raise an exception and then have parentheses there now we should get a server error and the page just breaks taking a look at the network you should be able to see a 500 status code here so the way you would check for something like this is you could say if response to a status is 500 or you can again have the catch all which is to say if response dot okay and then have the exclamation mark So if something went wrong or in other words it's not 200 to 299 throw new error and then pass in a message here so we'll say something went wrong try again later and then down after our final then we'll have a DOT catch pass in an arrow function here have the exception here set error e Dot message and then lastly on success we will remove the error so set error to undefined and inside of this if response okay I want to console log as well so I'm just going to temporarily leave a console log with the response and we will just say response so we should see in the terminal response and we can take a look at that I just realized one thing that the error is not showing up because the location where we defined the error is actually inside the condition for if the customer exists and this obviously is not the case in this situation so we probably want to take this error out and have it in its own Standalone conditional so that's going to be a lot better and now we should get that error message show up last thing let's just go fix our back end we don't need to do that and there we go our application should be good to go it's still pretty ugly but a lot of the functionality is there and I think everything is working but let me know if you've caught anything else that's weird we wrote in a lot of lines of code for this 100 and 50 some so there's definitely some things I've missed I'm sure last thing I would tend to do is just get rid of console logs I don't really like to leave those in for uh longer than I need them just for testing's sake as we all know cons logs are the best way to debug and test your application so let's just go ahead and get rid of these this is actually another spot where we would want to show the error message on the delete button so if there's a problem deleting it we can just say set error E Dot message and then on success before we navigate we wouldn't really need to update the error because we're navigating ah I don't know I'm splitting hairs now because I guess for consistency sake I would do this but it's kind of pointless because we're navigating literally right after so you probably don't need that line at all thank you so much for sticking with this video we've gotten a lot more into the details here and I'm kind of tired of working on this section so what we'll probably do is style the application next is to make it not hideous just enough to allow us to look at it without wanting to throw up that'll be good for me so let's do that next and then we will move on to something new thank you for watching peace out I'll see you in the next one what's up yo in this video we are going to be styling all the work we've been doing for the last numerous videos this is not a mandatory video for the series because if you're not worrying about styling right now then eh but I recommend you go through it just to get some practice pretty much right now it's just a list here with this uh plain inputs and some buttons that don't even look like buttons so we're going to try and go off of this that we created earlier on in the series where we have a nice form with these very clear buttons that's what we're going to mimic however we're going to do it on the customers and it's going to be a little bit different because we're not going to use this pop-up modal you could certainly design it that way if you wish however I'm going to go with the individual page structure that we've been doing we're just going to make it look a lot better so here we are in the customer component I also have the edit employee component up because I'm going to be referencing that if you're just jumping in you don't have the edit employee component no big deal basically we're just going to require you to type a little bit more no problem so I like to use copy paste whenever possible so first thing we're going to do is we're going to find our inputs in here and it's kind of easy to get lost so find the inputs and I'm going to surround these with a form is this required no it's working as is but I think this is generally recommended when you are submitting data so when you have a form you have the ability to give it an ID which is how you're going to reference it so we'll just call it customer and you can make any button submit this form using the form attribute so scrolling down we have this button save so you could say form and set this equal to customer what this will do is it'll make the enter button automatically submit the form so we can change our data hit enter and it saves however you may have noticed a refresh so that's one of the things with forms is it will submit the page and cause a refresh you see this question mark in the URL well we can fix this by going into the event handler on click go to the definition and this will have the event passed in as a parameter and you can say e dot prevent default I'll tend to call this e for event I also use e for error so you'll see a lot watching these videos so now let's try it out we will just change this and hit enter and it worked now you may also notice sometimes a form will have an on submit and you can pass in a function here which the function is called update customer so we'll say update customer and then other times the button will have an on click so scrolling down you see update customer both get the job done my general preference though is to have it in the form that way all the form functionality is kind of within one location and you don't have to go find some button which may be deeper in your code but optional now everything should work the same way updated data hit enter and it still works so we haven't actually made the form any prettier so everything looks the same but now that we're in a form we can give these labels and the labels will be used to describe what each input is for so we'll say label this one is going to be for the name and I'll do something very similar for the next input so I'm going to copy this and paste it down here changing this to Industry now you don't just want to leave it like so you want to associate the label with the input using a four attribute so that's going to look like this 4 and then you can set the ID that you want to associate it with here so we'll say name then jumping into the input we'll say ID is name so make sure those are all capitalized the same so those are now associated and that can also be helpful for things like screen readers Bots and form autofill and just making sure people navigate through your page correctly so the next one will say label for industry and we'll give that ID to this input as well ID is industry so now this is what it looks like name and Industry all right so we improved the HTML now I want to bring over some classes that we have to find inside of the edit employee feel free to just type these out manually pretty much just going to copy paste so here we have the form class name I'll go ahead and paste that here looks good and you'll notice that each one of these inputs is put inside of a div so the label's in a div the input is in a div and then both of those divs is within another div pretty obnoxious but that's how it's going to position things correctly Within These individual divs so I'm going to copy over that structure so let's just copy this first outer div or you can type it out yourself so right before the first label we will paste the div and I will also close the div I'm not going to worry about indentation too much yet because when I save it'll Auto format once we have everything fixed if it's uh syntactically correct so we end the div and now we're going to have a div for the label right here that's going to go right here and then close the div after the label right here and then lastly a div for the input so here is that div paste that there and end it down here perfect save and you can see it reformatted sum we're going to follow that exact same setup for the next input so I'm going to copy this outer oh I hate when it does that all right copy that outer div and we will paste that right here closing off the div down here perfect and then we will take the div for the label so that's all right here copy that paste it right here and this is one thing that's kind of weird maybe you guys could give me the shortcut if you know Visual Studio code is smart enough that if I type out for example a forward slash or anything it'll pop up with the ending but maybe there's a way to do that without having to type some random character but anyways it doesn't really matter let's go ahead and copy the input div and we will place that here so yeah this is just some obnoxious reformatting of our HTML but it allows us to apply classes for different visual structure so that is now our structure cool visually this is going to change it such that the label and the input are on the same line as this outer container is using flex and the items are going to be centered within that with a margin bottom six which will push the next thing down so it's going to look something like this and you can adjust however you feel necessary to get things to look right maybe we can change this so that it's 1 4 and this is three-fourths let's see what that looks like so it's going to bring these a little bit closer together let's do the same for the name so we will go up and we will change this to 1 4 and this 2 3 4. so that's what it's going to look like on small screens or medium screens if you zoom in it's going to change because we have Flex so it'll just bring it down to the next line now let's style the input to make it look a little prettier what we'll do is we'll head over to the edit employee grab the class names for the input and we will bring that over into our own input now we already have a class name here and I actually forgot to put name so definitely want to fix that there but as I mentioned previously in the series the difference between class and class name is not important right now class will work as well you'll just get a warning in the console same thing down here we will change class here to class name so far it should be looking better I'm going to zoom out just a bit so that's what it's going to look like the entire form seems a little close to the corner there so we can add some margin to it finding the start of our form we'll just say margin or actually m three I'll scoot it in just a bit so adding it to the form actually brought this stuff in but it didn't include the delete so instead we can add a padding to the outer div so let's go back into our code and in this div we will just say class name and set that equal to P3 and then get rid of margin 3 here and now the delete button is scooted in as well let's reformat this delete button to look a little better so we will grab some button classes scrolling down to the bottom here is a button copy that and we'll bring it over to our button so search delete it's right here and we will add class name and then we'll paste in these classes so now it looks like this same thing when we change data we want the buttons to look nicer and we can surround this button in a div so that it's on its own line so div and then put it close after the closing tag of the button and now delete will go down to a new line when these new buttons pop up let's go ahead and copy The Styling for the other button the only difference is the color so I'll copy that and that's what I'm going to use for the save so let's find that here we go so class name and set that equal to that now when we change the data it's looking a little bit better I think we could use the same gray for the cancel so let's go ahead and copy that and we'll bring that up to this button here there we go all right this is what it looks like now we can just add some spacing we'll just surround both of these buttons in a div so we can replace this fragment and then we can give it a class name so class name and we will set this equal to margin two which should space it out a little bit so that if we change something here it's spaced but let's just do on the y-axis or we could even just do the bottom so m b 2. and that will make it so that the delete button is moved down but we're not being scooted over on the left or on the top we could do something similar to get space between these two if you want so let's just add margin right to and that should do the trick there we go looking pretty good maybe just change the delete color a little bit maybe like a red we could also try a really dark slate and then make the text White so let's try slate 800. 800 I guess the text is already white so let's see what that looks like yeah it looks pretty good I think we can make this go back look like a button so we will find that here we are we'll say class name it's that equal to the same coloring as the purple button so now it looks sort of like this let's change the text to a left Arrow like this and get rid of that underline no underline so I just looked up left arrow and I'm able to take this and that's what we will use so paste that there and now it should look a little bit better so we'll close out of this and there we go we change it this is what it looks like I want this go back button to be inside of the same spacing as the form but I don't necessarily want it to be inside of that same div which is conditionally being rendered if a customer exists so an alternative here is to create an outer div and this is going to surround everything and that's going to have the class name p 3 can get rid of the class name here and then we'll just make sure we close this div so it's going to go all the way down to the bottom there we go and now these should all be in line and everything is within the same box here these are not being sized the same because this is a button and this is a link so what we do is we could actually put a button inside of our link so we'll say button and put the closing after the text and we'll take all of these classes cut them and put them on the button itself this is an alternative to creating an on click and then navigating we're going to surround it in a link now they look roughly the same and we should be able to hover over and click the link just the same so cool so that'll get you going in the right direction obviously it's not perfect but you can modify as you please to design what you want next up I want to style these here you could do it kind of like the employees page but I think I'm just going to keep it simple and just have these text inside of a button looking thing for each one of these so let's head over to our customers component so what we can do is instead of returning a list item inside of an unordered list we're just going to remove the unordered list and then what we'll do is we will change this list item to a div and then inside of the link we are going to create a button and we should be able to style the button similar to how we have our other link so we will paste over those attributes copy these paste save all right work in progress so let's just go ahead and give this div class name margin two and I'll space these out one last thing I want to fix is this add customer button is centered in the page and this comes from inside of the ad customer we have this margin X Auto so we can remove this that should get rid of the auto margins and put the button over on the left side of the page perfect not the perfectest of styling of course like I said I'm not the expert when it comes to this yet but it should get you going in at least the right direction so you can adjust this to fit your needs and style it as you wish definitely let me know if you have any suggestions for The Styling drop a comment below stay tuned for the next video and be sure to subscribe foreign [Music] we are back we're finally doing something new I'm getting kind of sick and tired of doing the other crap we were doing so this video we're going to start talking about jwts Json web tokens this is how you basically will do logging in and yeah that's pretty much it so that's how we're going to log in with an API so pretty much how it's going to work we'll make a request to the server we'll give them our username password the server will give us a token in response and a token you can just think of it as a sequence of characters and that's what we're going to include with our API requests so that we can prevent just anybody from using our API now you might still have public facing API endpoints and that's totally fine but you might want to have some that are private or customize something for an individual user so we'll start with the back end and then we're going to worry about the front end so we will have to build the capabilities on the back end to log in and get that token and and then on the front end we will build that login page the tool we're going to be using is called Simple JWT at Django Dash rest framework Dash simple jwt.readthedocs.io so let's just go ahead and install this what we'll do is we will open up our backend code you can close out of your server and do it in that terminal or if you're keeping that running you can just do it in another one just make sure you have the virtual environment activated and here's what we're going to do we're going to say pip install Django rest framework Dash simple JWT and as with all of our backend stuff we go into this in much more detail and my backend python course So Def check that out if interested you can check that out at codebreakthrough.com backend.python all right enough advertising once you have that installed we can open our settings and we just need to define a few things in here I don't think the location is significant I'm just going to Define it after this middleware section and we're going to say rest framework in all caps with an underscore and set this equal to a dictionary with default Authentication classes colon and in here we're going to parentheses with a single value and we'll put a comma there at the end if any were added rest framework simple JWT dot authentication dot Capital JWT authentication so yeah if you don't have this memorized by the end of the video then you're weak you should probably just call it quits man I don't know if you're going to make it as a developer now what we can do is we can make a new path in our URLs to get a token so I'm going to Define this hmm I don't know probably yeah just first thing path and the path here is going to be slash API slash token and we're going to import some stuff so we'll say from rest underscore framework underscore simple JWT dot views import token obtain pair View and token refresh view now we can use these views token obtain pair View and this is going to be invoked so add parentheses here and we can give it a name we'll say token obtain pair and we'll understand better what all this is in a minute so just follow along for now we're going to have another path the second path to refresh the token API slash oh forgot to slash do we want to slash at the beginning no no slash at the beginning here token slash refresh slash at the end there we go and then this is going to be token refresh View also invoked and name is going to be token refresh so basically we're adding two new URL paths to get a token and refresh a token so let's go try this path in our browser see what happens and oh I totally forgot to close out of this wow this is incredible okay where was I let's close out of these here and we're going to go to API slash token and then we might need to restart our server or check if we have any problems view must be a callable yeah so we need to pass in dot as View my bad all right now let's just restart our server here all right seems to be working let's go ahead and refresh this you'll see we have a username password that we can pass in make a post request and we'll get a refresh and access token where did this username and password come from it's the same user that you use to log in in the admin site so localhost 8000 admin we Define this user inside the users table with create super user in the terminal from an earlier video so if you don't remember how to do that you can just say python manage.py create super user and that'll go through the process of creating your first user which can then be used to log in to get a token so we have an access token and a refresh token we will include this access token with our requests to restricted API endpoints what exactly do I mean by restricted API endpoints well we want one so that users have to be authenticated to access so in earlier videos we built a customers page that we could list out our different customers and get information about them what I want to do now is you have to log in to access that page and interact with the customers so let's go ahead and restrict those API endpoints so that not anybody can use them so here we are in our views.py and we're going to use a new decorator similar to how we have this here so it's going to look a little bit like this just a bit different but it's another decorator so we can just add it to this rest framework.decorators import permission underscore classes and then we're going to have another import from rest underscore framework dot permissions import is authenticated The Decorator is going to look like this we'll say at permission underscore classes and pass in similar to API view in a list where the only thing in here is going to be is authenticated so that's what we're going to do and we're going to put that on any of the functions in this file that we want to require people to log in with now I have one really important thing that I wanted to call out so make sure you're paying attention this API view needs to go above the permission classes otherwise it's just going to be ignored so the API view is going to go on the top now we can go test this from our browser and now we can go to any of these API endpoints so we'll say API customers authentication credentials were not provided uh-oh so I actually need to take the data here and include it with our request now it's not really easy to do inside of this user interface so we'll need a different way of trying this out so you have two options here you can make the request from JavaScript like we're building our front end this is kind of jumping to the next stage where we're moving over to the front end I personally prefer to kind of make sure our back end is working the way we expect so I'm going to grab an API testing tool called Postman Postman is going to allow us to include a lot of extra stuff with our request so we'll download that and try out our request there first Auto search Postman download because I also have an online version which isn't going to work for a local host so you'll definitely want to make sure you get the download version so Postman is always changing they say a new release every week but it all does pretty much the same thing so if you're not on the same exact version it's going to be fine so I'm going to open my existing Postman it's gonna look something like this and you can organize things into collections and also workspaces I'm just in like a scratch Pad version I don't really keep track of all my API endpoints but that would be a great way to test your apis for for example regression testing or just to make sure things are working the way expected just to have a good list of all those different API endpoints that you can call really quickly so we're going to do is just type out localhost 8000 slash API slash customers hit enter it says authentication credentials were not provided exactly we're respecting but now we can go into authorization and what we're going to want to select from this list is Bearer token and we're going to paste our token in here so paste that value there now when we hit send you should get uh okay I got wrecked so token is invalid or expired I just took too long making this video not a problem though so I'm just going to go in log in again get a new access token so we'll copy I just tell you how this is presented here so I'm just going to copy this value paste that thing right here hit send and there we go we're able to access that API endpoint we will visit our other API endpoint which was API slash token slash refresh and here it says method get not allowed but we can make a post request here by pasting in a refresh token and hitting post this will give us a new access token so basically this refresh token allows us to get a new access token so our original access token expires frequently but we don't have to log in again with our username and password we can just keep track of that refresh token and use it as needed this will basically give you access for a period of time let's say it's 30 minutes but that 30 minutes will restart if you're still active because we're going to use that refresh token so if you go away from your computer for 30 minutes then you'll be kicked off because at that point your access token and your refresh token will expire that's why when you're on a banking app for example you can keep using that app as long as you want without having to log in again but if you're inactive for a certain length of time it'll kick you off that's all I got in this episode which is all about setting up the back end for this in the next video we're going to talk about the front end so looking forward to that I'll see you then be sure to sub s peace out what up everybody this video we're going to be dealing with front-end authentication so we already did the back end stuff in the previous video if you want to check that out I'm also going to give you the code so that you can get started with this video right away if you're just jumping into series Midway so first off we have the back end repo here and here is the commit hash if you want to go grab the back end code and then for the front end here is the URL and the commit hash and as a reminder of what to do with that you can go to the URL and then go to the commit history and find that exact commit hash and get the code at that moment in time and with that I think we are ready to get started so in the previous video we set up jwts Json web tokens and we have the ability to request a token and then the ability to use a refresh token to get a new access token the very first thing you should do is try to figure out what happens when you try to access a URL that you don't have access to so say you're not logged in and you try to see all of the customer data the API endpoint is API customers and this is what you should get if you're not logged in accessing this URL from the front end should give you something very similar we're just going to see that 401 in the network request so visit the network tab do a refresh if needed and you should see that right there so you get 401 unauthorized this is an HTTP status code and you can have some specific behavior defined in your front-end code to deal with this HTTP code so taking a look at our back end we're currently just accessing that URL we're not checking for anything we don't have a catch so any errors are just going to break our application and we're not going to get the effective Behavior so what we need to do is once we have the response we can expand on this by using curly braces and this will allow us to Define multiple things inside of this function body and you will just need to add a return now above this we can check for a specific status code so we can say if response dot status is equal to 401 we can do something specific in this case we can navigate and the path we're going to navigate to will be slash login so basically telling people that they need to get a new access code so basically pointing people in the right direction on how to get a new access token so we will Point them to slash login and this is going to be the use navigate hook so we're going to need to import that and it comes from react router Dom so right after link we can say use navigate and then we'll create a variable for this so that's going to look like const navigate is use navigate that's all you have to do and it should work so you can see it already brought us to the login page so when we visit customers it'll take us to login you might see a little flash of data and you can work on the user experience there but it's not really relevant because the data is being shown does not contain any customer data because we're not even able to hit that URL we just have that add customer button showing up by default and then it redirects so quickly something similar should happen when we visit a specific customer now for this you might need to have an ID that exists memorized so customer slash 12. similar thing we're getting unauthorized but it's not doing the redirect so we will Implement that for a single customer as well the code is going to be pretty similar so you can copy it from here if you want or we could just get some more practice writing it out this one we are checking for a 404 so we can just have an else if down here and this will check for a response status being equal to 401 not 420. oh man what am I what am I doing here I'm like trying to type out status codes and I'm like all right we're going to type out 401 oh no not that cheese 401 and then we will navigate same idea so slash login let's check make sure that works so we visited the customer with 12. and it will redirect to login now obviously if you forget the customer ID you can just go to your backend code and remove this permissions required and that will allow you to access all of the customers very easily or you can just use Postman and attach a token which we showed you how to do in the previous episode but just showing you that if you just need to check real quickly I'm going to bring that back now let's talk about the login Behavior we have something pretty similar to find automatically with the views that came with the Json web token package so if you go to API slash token you can see the ability to post a username and password so we can replicate this Behavior creating a form where someone passes in a username and password and then we log in and we include that data in our post request to get a token so the next step is we're going to create the login form make a request to the back end to get the access token I'm going to copy over a very similar form from code we have because it's already styled and it looks pretty nice you can build it from scratch it's not too complicated you just need a form with two inputs for the username and password we're going to set the first one to input type text the next one input type password which will mask the text from people's eyes so let's go ahead and get that form started I'm going to take it from an individual customer so scroll through here we have a pretty good form with a lot of different styling here so this form right here I'll just minimize and copy this code bringing that over into a login page we're going to go to Pages new file login.js export default function login and we're also going to need app.js for the routing so let's go ahead and Define A New Path which will be route path slash login and this will also have an element the element will render the login component save and we will import that so import login from dot slash Pages slash login cool so now we can just have this login return something and we should be able to see it on the page so I am going to say return and inside of here I'm going to paste our form so yeah definitely complicated I'll zoom out so you guys can see all the code here now it's so zoomed out you can't even see anything but those are the classes those are just for styling not essential to the functionality of this form so I will Zoom back in I think that looks good let's save modify this a bit because we're not going to have an update customer so instead we will have a login function we can Define that up here above the return it's a function log in and we'll just leave this blank for right now we're not going to have this state here so I'm just going to temporarily remove this with just an empty string and we're going to empty out the on change function and we will fill this in with the appropriate State when we get there but for now I just want to get the form to show up on the page so that should be a little bit better and next thing we might need some imports we can see as we visit the page so far so good no Imports needed now we can just update this form appropriately to have username password so the first one username also going to change the ID so it just makes sense username ID is username next up we have the industry so this is going to be password password and so we type password there we go now whenever we do have the ability to type in a password it will be start out so now we need to figure out the state so that these things work correctly so we will go and Define some State up here right before the login import use state from react and then we will say const username and set username comes from use state with no default value we're going to do something very similar for the password so we'll just copy paste password set password and then I'm just going to add some margin around here so M2 which should just scoot the form in a little bit now we just need to associate the username state with this input that's going to be in the value section so the value here is going to be username and the event is going to say set username with e dot Target but the suggestion was bubbles not sure what that is but e.target dot value and we will do the same thing down here for the password so the value is going to be password and then on change we will update the password so set password to e dot Target dot value okay let's see if we can type those in Now set password is not defined so maybe add a typo set password okay now it autofilled from my auto filling but you should be able to type in username here and a password Here great what we need to do now is we need to submit this form with a button so let's go ahead and Define a button we can just put this within the form and for The Styling I'm just going to again take classes from an existing button I already have so we'll go over to customers I will take this save button classes and paste these here these are Tailwind classes so you can install Tailwind if you don't and use these or you can look these up in tailwind and see the CSS styling and apply them manually then we just have to put a button login and that should make it look like this now we can have a form on submit so we'll scroll up to the top of the form on submit is log in so we can Define this login function this will first start with a URL which is going to be the base URL we've been using for all of our components so let's import that that's going to be defined in a shared file so we'll say base URL from dot dot slash shared so that'll bring us up a directory right now we are here and the shared file is right here all it has right now is a URL no big deal you can manually type that in here if you wish I just like to have the URL in one place and then we're going to add to this I think the slash is already attached here so we don't need to include that API slash login this can be then used inside of our fetch so we'll throw the URL in there dot then dot then and we will just Define functions real quick here and then we can just put the parameter so this is going to be the response and then we'll return response.json into a variable called Data so let's expand this function and say return response dot Json this is kind of the format I do for pretty much all of my fetches and then I just modify them for now let's just console log data save now let's check it out see if it works we'll fill in our username and password this was defined in the backend code with pythonmanage.py create super user so let's go ahead hit login one problem is it did a refresh which I always forget to do this we need to have e dot prevent default and that's going to prevent a page refresh and then the event is going to be stored here that's how we can access it on that event so e dot prevent default now let's try logging in so we're getting a 404 and that's just because we have to make sure we're using the correct backend URL which is actually API token not login so you can change the url for the back end independent of what the front end URL is right here it's login so the backend URL could be slash token I'm going to leave that ending slash there you can configure that in your back end too if you need that or not so we should be able to log in now let's check it out method get not allowed at this point we are hitting the correct URL we just have to make sure we're using the right method and passing along the data that was typed in for the username and password let's expand on our fetch we're going to say what method we're going to say the type is application Json and then we will include a body which will Json stringify our username and password it's going to look like this after the URL we're going to have an object this is where we say the method and it's going to be post then we will have headers this is going to be an object but the first thing in here being content type and quotes because we have a hyphen there this will be application slash Json and then the next thing we're going to include will be the body and that's going to be Json Dot stringify and we can build an object in here so the first attribute we want will be the username and that's going to come from our state username and then lastly the password which is going to come from our state variable password okay so we can make this request we can check in the console to make sure everything is sent correctly let's hit log in we are getting a new response no active account found with the given credentials which is closer to what we want if this happens to you it just means you got to get the correct username and password which I currently do not remember what it was let's check our request just to make sure everything is being sent correctly username password we will go over and create a new super user because I forget yes that password is okay all right we got our super user created let's go ahead and try to log in with this login and there we go check it out we got a refresh and access tokens down here you can check out the request here this was the payload the body you can also see your headers down here and then lastly you can see the response we're officially logged in but we're not doing anything with the access token so the page is going to act exactly the same we now need to take that access token and include it in any of our requests and also we're still on the login page it doesn't look like we've actually done anything so we should navigate to a new page these are the things we're going to improve on and we're going to start with that in the next video so we didn't get the complete login capability finished in this video but it's definitely a lot of material so it just makes sense to split it up into a couple of sections hopefully this has been helpful and you've been able to follow along stay tuned for the next episode [Music] foreign this video we're going to talk about something that's really important in web development and that is local storage you can think of this as a little database that stays in the browser of the client so if there's some information that you want to store but you don't want to store it on the server you can instead store it on the client in local storage now what would you possibly want to do this for well in our example when we give an access token so that people who log in can use our API we want that access token to be used to Route our application and that's going to be sent with every request so in this situation I'm viewing your application from the client I get an access token I want to take this value save it somewhere local storage and then use it for my future requests using local storage is actually quite easy we'll show you in our code here where we have the console log of the data that's what's showing up down here instead of console logging it we can add it to local storage so you'll just say local storage dot set item you can see the signature here takes a key and a value if that key and value doesn't already exist it'll create a new one so what we can do is we can pass in the first thing and let's just call this token and then second thing we're going to pass in is the actual data so let's just pass in data directly like that and now instead of console logging data let's console log local storage now that we're console logging that we will go ahead and log in you can see now storage is being displayed in the console one of the properties on here is the token now the token is an object with multiple properties so the string representation here is just object you also have the ability to use multiple properties so for example we could create this to be the access token and I'm just going to leave it as access and then you can say data.access we could do the same exact thing for the refresh so we'll say data dot refresh and change this to refresh now let's go ahead and log in take a look at our new storage and we have the access and the refresh token there directly available token is still there so you'll notice that it persisted between each execution so some things you might see are whether your website is in dark mode or light mode that could be stored in local storage you may also see if you have some for example a documentation site and you switch between multiple tabs well that change might be reflected across the page in all of the other pages so that decision can be stored in local storage local storage is saved temporarily but it's not guaranteed to be saved forever you can easily clear local storage by saying local storage dot clear this is a function call hit enter it'll say undefined because the function doesn't return anything and this is kind of like a read a vowel Loop but now if you take a look at local storage the length is zero and there's no properties there this is pretty similar to what you'll do when you log a user out you will just get rid of the access and refresh properties and now that we have these values we can use them in another request to prove that we have access to the API so let's head over to the customers and we'll start here where we make a request with the URL we can include some extra information specifically as we've done before you can include the method this is a get request and get is the default so you don't have to actually put anything for the method but you can put the headers here and inside of the headers you're going to want to say content type and this is going to be application Json and then the next thing is authorization which I think we can just do without quotes since there's no hyphens and this is going to be Bearer and then we will include the access token which we will get from local storage this will just be local storage dot get item and then you will pass in the key which was called access so let's save and try this out we're going to log in again just to get a brand new fresh access token and now we should be able to visit the customers that works the individual customer API call is not including the access token so if I click on any of these it doesn't work and we're getting a 401 unauthorized so you can now practice by putting the access token on the individual customer API endpoint as well so let's go ahead and do that real quick we're going to go to customer and this is going to be very similar to this here so I will copy these headers and scroll up to the fetch we will include an object here headers and then paste those values now they should show up so let's head over to our customers page click one and the data shows up we can change it locally here but the save and delete methods will invoke different functions in our JavaScript code and those don't already have the header so what happens is if I try to save I get another 401 unauthorized in another note whenever you do get a 401 unauthorized you should let the user know or automatically redirect to the login page so let's go fix that for the update as well as the delete so it's going to be very similar to this pattern where we navigate to log in if there's a 401 status code so let's grab that section first um I will take that there and let's go find the other fetches so we can say if response dot status is 401 we will navigate to login same thing for the delete which I'm just going to jump to that we will do a very similar thing here if the response is 401 navigate to login that should fix the 401 problem now we just have to figure out how to attach the access token so we're going to copy these headers here and include those on the other fetch requests so it will go down to fetch replace these headers with the new ones and same thing for the delete fetch I always lose there it is paste that there looks good let's try it out googler just for example save that worked and then we will delete yay now if you want to simulate what it might look like if your token expires you can just change the access token in the console and see what happens so you can say local storage dot access and set it to something bogus like five now when we try to change this we hit save it redirects to the login the same thing should happen but we might have to log in again so we'll log in visit the customers go to one of these then change the local storage.access then hit delete and it brings us back to the login thank you for sticking through part two of our login capability we still have a lot to do with logging in so definitely stick with it stay tuned for the next episode we're really starting to see things come together I'm really excited I hope to see you there peace out foreign welcome back to your react series we're still talking about the proper way of logging in in a react application so we just did two other episodes on logging in and this is all about creating the form and taking in the access token into the local storage but the problem we have is that our form doesn't redirect to a new page after we log in right now if we visit the login page from another page we hit log in nothing happens even though we're technically logged in at this point so this is a great opportunity to learn about a new hook called use location and we're going to learn about passing state with our use navigate hook so that doesn't mean anything to you don't worry that's what we're talking about in this video so we have two options here we could navigate back to the previous page they came from which is what I would recommend or alternatively if you want to keep it real simple you could just navigate to some home page you know maybe they have some dashboard that is a very simple way to do it because you'll always be navigating to the same path and you don't have to worry about passing paths and state between different components so the first thing we're going to talk about is how can we send information to the login page that says where we came from and that is going to be done by passing state with navigate so this is what it's going to look like within our code we find some location where we are navigating to the login page and navigate has the ability to take another argument which is going to be an object inside of here and this is important you're going to have state the property name here needs to be State now inside a state we're going to have another object where you can place whatever properties you want so for example we could say previous URL and then pass in some value like slash customers now we are currently in the customers component so slash customers is kind of like our current URL but when we pass this to another component and we go to a different page it's really going to be the previous URL from the login perspective it's the previous now within the login page we can talk about how to get that information so this is going to require a new hook so we'll say import and it'll be called use location from react router Dom and we will create a variable for this so we'll say const location is use location so this location variable should have the information that we passed in that state property however just to see this I'm going to have a use effect which will allow us to easily write something to the console so we will also need to import this from react so use effect and inside of this function a little console log location so here's how it's going to work you visit a page it redirects to the login page we have an object down here which has the state property and you can see the previous URL in there so when the user logs in we know the appropriate place to send them should go to slash customers now we hard-coded that slash customers inside of our customers component we'll talk about how we can generate that value here in a moment for now let's talk about how we can navigate to that page pretty much we just need to go into the state object and then grab the previous URL property saving that and now we should adjust the slash customers so that is the value you want to use when we navigate so now let's go into the login event handler and navigate to slash customers after we are done with the fetch so let's go in and find where that form is submitted here is the fetch finally we got everything good to go we're not going to need that console log anymore but we are going to navigate and pass in location dot state DOT previous URL that should do the trick we can get rid of this use effect that was just for demonstration purposes and the last thing we're going to need to do is we're going to need to create a variable for this navigate so we'll say const navigate and this is going to say use navigate which will need imported from react router Dom use navigate now everything should be wired up so let's go visit a page it takes us to the login page we log in it takes us back to the customers page this took me some time to figure out how to do it and I wanted to give a special shout out to webdev simplified who gave me some tips there's a few other ways you can do this so feel free to do some research on what way you would like to do for example navigate you can pass in a negative number to go back in the user's history one reason I didn't want to do this though is that if they came to that URL directly well it might take them back to a previous website that they were on this seemed like the best solution for me now I want to talk about how can we generate the current URL when we pass in the previous URL so right now we are hard coding slash customers in this previous URL what I want to do is basically say the previous URL is the current URL so how can we see that they are currently on the customers page well this can actually come from location as well if you take a look at our previous object we printed here we have the path name slash login so we should be able to say location dot path name so let's try it out we will import use location and again this is going to come from react router Dom anytime we're doing anything with links or navigating or routing that's react router Dom and we will create a variable so const location is use location and now instead of current URL we will just say location Dot and the property we are looking for is path name you can see it right here so let's go ahead and type out path name save let's try it out so we will first log out by manually setting our access token to something else now when we visit the customers we're already there so let's do a refresh takes us to the customers page redirects to the login page we hit login it takes us back to the customers page so far so good now all you have to do is copy this Behavior across any Pages where you redirect to the login page so I'm going to copy this object here because we're going to do something very similar for these other routes and pretty much any time we navigate to login we will want to have the previous URL so there's three from the customer and one from the customers so we got this this one was old and was for demonstration purposes there's actually no back-end requirement for a login but you could of course add that in here as well it looks like I need a another curly brace there let's go add this to the other pages paste that here here and here now say file save all let's try it with an individual customer now so we will visit oh of course we have to import the use location ref and create a variable for it silly me so let's go up here use location and we'll just create the variable cons location is use location and we will copy this line for the other Pages as well so create that there I kind of try to keep things consistent in my spacing in the order in which I do things but I'm not perfect and we will need to import that here as well so react router Dom use location and then I'll just make sure everything is saved and now our site looks to be in working order again let's go ahead and log out by setting our access token to something now if we visit a specific customer let's say customers 12. we log in and it takes us to customer 12. if you're not sure the ID you could go back to your customers list and check their IDs but yeah so far it seems to be working we could also check the dictionary one just in case this is using an external API so it really just doesn't even make sense to have this navigation to a login page so I'm not going to worry about that for now we just had that for a demonstration earlier on in the series so we need to consider the situation where you visit the login page directly and you don't have a previous URL so you can test this out by taking this path and pasting it in a new tab and now we didn't come from any other page so when we log in we get an exception Throne cannot read properties of null so we're trying to read previous URL but state currently is null so again exception and if you needed to you could go through here and console log each item one at a time so we would say console log location console log location dot state and then console log location dot state DOT previous URL so the third one here is what's going to throw the exception so when we try to log in we get three console logs this one this one and this one the first thing exists but state is null the next one state is obviously null and then we get the exception so the third one gives the exception but the real problem is a layer up because state is null so to fix this you can do optional chaining and you just put a question mark before each of the dots and in this situation if you try to access something on something that is null this value is just going to be undefined instead of throwing an exception so now in the console we shouldn't get any exceptions so if we try to log in we just get null and undefined we're still getting the exception here but that is actually coming from navigate so we can do the same exact thing here but this isn't going to work quite right because you can't navigate to an undefined so what's going to happen is we log in and it's trying to navigate to an undefined path so the fix for this is now to do a ternary and we're basically going to Traverse through this structure using the optional chaining and if that value exists we'll navigate to it otherwise we'll navigate to some default page so what we'll do is we'll say question mark and if that's the case we will navigate to location dot state DOT previous URL we don't need to do the chaining now because we know it already exists if this is not the case then what we need to do is just navigate somewhere else such as the default customers page or some dashboard or some general page and now when we log in it takes us to the customers page so that is how you make sure your login page is not completely broken if you try to access it directly now we can get rid of these console logs we're not going to need those and there you go so that my friends is how you will navigate to login and then redirect back to the previous page thank you so much for watching hopefully this is helpful now we got to take a look at logging out and how to conditionally render things like login or log out in the header and various other things like that so stay tuned things are starting to come together it's looking quite nice you're kind of looking nice [Music] hey everybody in this episode we're covering a very important part of react and that is use context when first learning about this it can be a bit confusing but once you understand why it's valuable and how it could help your application it makes it just a bit less painful learning the new syntax and the new structure so let's first talk about what it is for and why you might want to use it so if we are working with some State and we want this state to be used across the entire application that is where use contexts can come in handy this will prevent us from having to pass props down multiple layers when might you want to use this I think of two really good examples the first one is a theme across your website most of the examples out there for use context are going to be switching themes and the other example I have is for logging in so instead of trying to figure out if a user is logged in or logged out on all of our different components throughout our website we're just going to create a context at the root level and Surround our entire application with that code so whether a user is logged in or not will be accessible throughout the entire application this is going to make it a lot easier to do things like modify the header to say log in or log out so here we have this calendar button but it doesn't really do anything instead I'm going to change this to a login button or a log out button and which value is shown depends on the current state of that user and pretty much anytime you want to customize things throughout your site depending on whether that user is logged in you could use use context for that so we're going to take it pretty slow make sure we understand everything the first goal is to create that state at the global level and we will try to access that from one of our components and I'm kind of do using these hand motions because we're basically going to surround our code we'll have the start and then we'll have the end and everything in between is going to be our application whenever you want to do something like that you'll probably want to start looking at the app app.js file so app is our outermost component so you can imagine if we surround everything within app this whole section with a context we should be able to access that value within any of these other components so to do this we're going to need to import something from react so let's go ahead and remove unused Imports and then I'll say import and this is called create context from react to use this we're going to export a const so export cons and we're defining this outside of the app function you might be used to defining the variables within the function but because this has an export we're unable to do that export is going to allow us to import this into other files and we will call this a name to describe what we want to store such as login context and this is going to be assigned an invocation to create context so we defined our context how do we actually say hey we want to put it down here it's going to look pretty similar to rendering a component we're just going to say login context dot provider and this is important because we're going to provide a value that's going to be accessible throughout all these other components so we will take the ending tag and move that down to the very bottom of this return now all we have to do is provide a value here and this will typically come from some State variable so let's go ahead and create some state so use state and inside of here we'll say const logged in and set logged in and this is eventually going to be associated with the access token that the user should be maintaining but for now we're just going to hard code a value true as the default and pass in logged in so that is step one this is the providing end how we deliver a value to these other components now we have to talk about how do we get that value inside of these components to do that let's head into any of the components I'm going to start with the header because that's where I'm going to try and toggle this to say logged in logged out so it makes sense to start there we'll go into the header the way we use the context value is first importing something so we will import use context from react and we will create a variable here inside of the header function const logged in and this is going to come from use context and you're going to pass in the name of the context which was log in context now the name here doesn't exist until you import it so we're going to have another import and that's going to be login context from dot dot app all right so let's take a look back at app real quick that is the thing we created here this login context we're exporting it which allows us to import it over in the header so there's two things we need to import here now when we say use context we pass in the name and this call is going to return whatever value we stored in it so this should be true or false we can check that real quick with a use effect so we'll say use effect and I'll write that out real quick here use effect and in here we will just console log logged in so this is basically going to tell us if we successfully grab the value that was provided to us in the app component let's check it and you can see we get true in the terminal so that was step one we created a context and provided a value and we were able to access that value in another component let's try again but this time I want to put in the functionality to toggle that value let's say the user's access token expires and we set the logged in to false for this we're going to need to provide an additional value to our context because not only do we just want to display the value we want to be able to change it so this is going to start up in app.js and when we pass this value in we can actually put two values here so we're going to make an array and the second item here is going to be set logged in now anywhere inside our application we should be able to set the state as well let's talk about how we can access these values in a new component let's go with customers so I'll go to the definition it's going to be very similar so we will import use context from react and then we will import the name login context from dot dot slash app and then inside of our component const and this is interesting because we're going to Define this almost exactly like use State since we have two variables now we can say logged in and set logged in and this is instead of you state it's going to be use context and we're just going to pass in login context so very similar to The Way We Define State just that this is over here a little bit different now that we have the logged in and set logged in available to us if we get an unauthorized response from the back end we can toggle that state to say that the user is not logged in this can immediately update the user interface to change what is being displayed so let's just try this out let's go ahead and find where we might get an unauthorized and we will invoke set logged in to false so let's save that and let's try this out we will head over to customers and you can see an immediate change in the state so the state is being printed from the header we started off with the value being true when we visited the customers it realized we got unauthorized and it changed the value to false let's see if we can now use this capability to our advantage to automatically update this value to say login or log out so we will Define this inside of the header the way this is done is a little strange because the data is just in this array and then it says looped through down here somewhere below hopefully yours is not quite as complicated what I'm going to do is I'm just going to remove this one here so it'll Loop through those three we get employees customers and dictionary and then I'm going to manually code in the other one which is just going to make it a little bit easier so we'll have an additional nav link after navigation.map we will have another nav link spacing here is Jank so let me just try to improve this a little bit we're not going to need a key because we're not in a loop this is going to go to we'll start with it just saying log out so slash log out now we're never going to have to worry about this thing being active or inactive so instead we can just assign some class names directly in a string this is going to simplify our code a lot so let's go ahead and grab these classes here paste that here and those ones are shared whether it's active or not and then if it's not active which is the style I prefer that's what I'm going to take so I'll take these paste those there and we should be able to get rid of this entire class name section lastly we can just change the value to logout all right so that should be our code let's take a look cool so it says log out we got the basic structure we may have to do something similar for mobile so right now it's still not displaying log out so we're going to have a ternary here now as well for the display so we'll say logged in if so we're going to navigate to Vlog out otherwise we will navigate to slash login now we're going to replace this log out here with a ternary so we'll say is the user logged in if so we will display log out otherwise we will display login we'll save let's take a look and you can see it says log out one other thing I need to do is I need to change the way we are importing logged in because currently it's just referring to an object so we instead want it to be logged in and set logged in okay that should be better it should just be true or false now so let's just start over so we'll refresh it's currently true and says log out we visit an unauthorized page and it automatically changes to login that pretty much summarizes the functionality I'm just going to copy that setup for the mobile version so we have this nav link here I'm going to copy that and we have a different Loop down here for mobile so after the navigation loop I will paste that and then I'm just going to do the same thing where I just copy the mobile classes so we'll take this and we're going to replace this entire thing here that and if it's not active and those are the ones we want so I'll take that there we go so now we have a login button it brings us to the login page it seems to work well now we can just set the is logged in to false anytime we get an unauthorized if you want to practice you can try it yourself from the customer page so give it a pause otherwise we're going to go through here so hopefully you are a pro by now we are going to import use context and we will also import login context from dot dot slash app we'll access that within our function const logged in and set logged in coming from use context login context now let's go ahead and set logged into false anytime we get a 401 set logged in to false and we'll find anywhere else that the same thing happens so here and down here we will remove our access and when we do something that we're unauthorized to do this should change to log in there we go a final change we're going to want to make is that when a user logs in through the login page we will want to set logged in to true so we're going to go through a similar exercise here on the login page so let's go ahead and import this will be import use context and then import and this is going to be login context from dot dot slash app and now we should be able to grab a reference to the logged in value similar like we've done in the other pages so it'll look just like that and now when we successfully log in right before we navigate we will say set logged in to true Let's test this out make sure it's working I've already cleared local storage it says login we're on the login page hit login and it says log out at this point we're so close to done there's just a few things we need to wrap up specifically the default value inside of app.js it's currently just true the other thing is within the header we need to Define custom behavior for a log out button and we no longer need any console logs throughout our application so the default value and logging out is what we're going to cover in the next video because these are actually going to be very similar so that video was pretty wild lots of stuff talked about in this episode so hopefully you have a decent understanding and hopefully we weren't too scatterbrained about this but I think overall we got a good application going and it seems to be working so thank you for watching stay tuned for the next episode [Music] hey guys in this video we're just gonna jump right into the code because this is like my fourth time trying this video and every time I try I screw something up it's kind of the Story of My Life so the goal of this video is to talk about two things this default value when you visit the page for the first time and the log out capability right now we have the logged in set to True by default which doesn't really make a whole lot of sense I mean if you visited the page for the very first time it's going to tell you to log out that's a little strange but the opposite doesn't really make a whole lot of sense either because if we set this to false and you know you literally just log in right and then you visit this page in another tab it shows you the protected route but tells you to log in well that's not what we want either so it really seems neither of those work so really true is better I think because worst case scenario just sends you to a login page but neither is ideal and the better solution is to check local storage for an access token this will at least give us a little bit more accurate results the only consequence is it may be expired so the long-term goal is to use refresh token and if it works stay logged in otherwise send to login page so that way they have a more specific destination or goal which is either they're logged in or they're not whereas what we're doing now is just kind of assuming one or the other so what we'll do in this first video is this top one here this will be pretty similar to the logging out which will just remove everything from local storage the refresh token is going to take some building out so we'll do that probably in the next episode so this is what it's going to look like we will ask if they have locals whoa I need to calm down all right local storage Dot access if they have that value then we will say true otherwise we will say false so let's just go through this example so let's go ahead and visit this page for the first time it checked our local storage realized we had a value and it says log out similarly if we log out well which we haven't built that behavior yet gosh so to simulate that we'll just go into the terminal and say local storage dot clear and now we'll remove the access token now if we visit localhost but instead of customers we access an open page such as the employees page this is fine and it tells us to log in because we don't have the access token so it's at least a little bit of a better Behavior than what we had earlier the only possible downside is if we have an access token that is expired so you can simulate this by going into login and setting the access token to a specific value such as five so this is not a valid access token so you can imagine we had the original access token and it just expired enough time has gone by which you can configure that in your back end but now we no longer have a legit access token but we have something and in that situation when we visit the site on an open page it's going to tell us to log out and it'll continue to say log out until we access a protected route so not the worst user experience ever only real downside is if you end up taking a break from this site and you come back a long time later it might just say you're logged in and then as soon as you click a protected route it's going to ask you to log in even though it just said you were logged in so not the best user experience but better than what we had and that's where we're going to stop with the default in this episode so we have implemented this Behavior now what I want to do is I basically want to clear local storage whenever we log out so let's go ahead and build a log out button right now we have this nav link and you can conditionally Define and on click on here so you could say on click and this could be set to a ternary and this would check to see if logged in has a value and if it does you could execute some function and otherwise say no so that's one way you can do it and then you might need to change these conditionals throughout so that's a little bit more complex what I'm going to do is I'm just going to completely render a different nav link so many spaces there depending on whether logged in exists so it's going to look like this logged in and if so we'll render this nav link otherwise we will render a different nav link which is going to be pretty similar so I'm just going to copy this one here copy paste and this way we can avoid a bunch of ternaries and it might just be easier to read so in this situation if logged in is true we only need to worry about it saying log out so we can get rid of the ternary and simplify this code a bit classes will stay the same and all we have to do is have this say log out don't know what that's from sometimes that appears I don't know I think it's part of the prettier extension doing something strange but we'll remove that now the other option is they're logged out in that case we only need to display log in so we can get rid of everything else and same thing down here and we don't need this quote sorry so right now both of the buttons are being displayed the fix for this is just to surround your ternary inside of curly braces so it'll look like that and now let's try this out so we log in hit log in it changes to log out now if we reset our local storage and access a protected route it tells us to log in so it's working but now we can easily go in here and add a custom on click for the log out so we will go up here say on click and we will Define a function in here first thing I'll do is I'll just console log ging out just so we can confirm that we're hitting this so we hit log in takes us to a page and we hit log out it says logging out we don't necessarily need to navigate to a new page so we can change this to a pound sign alternatively you can navigate to the login page after you log out so all we need to do now is to say set logged in to false and I want local storage to be cleared so local storage.clear all right let's check it out see how this works so we'll visit some page we hit log out it says log me out and it changes to login but the actual page we're on doesn't change so I think it would be more appropriate to redirect to the slash login page so now let's first log in it'll take us back to customers we hit log out it takes us to log in and it changes us to login and now if we open a new page it should still say log in because we also cleared the local storage at this point I'm pretty confident in this function I'm going to remove this console log so we've definitely improved the beginning and the end of the login experience in this video there's just one change that I want to make and that is anytime we set the logged in state to false we're also clearing local storage which will just kind of keep everything in sync and then if we access the page again we don't have any lingering expired tokens that aren't going to work and that might mess up the user interface and then in the next episode we're going to take a look at that refresh token and how that works so let's go into our code and we will figure out how we can clear the local storage whenever we set logged into false pretty much we are working with a function and this comes from if you look up here we have set logged in from use context and if you go into the login context you can actually Peak the definition this is just state so we have a set logged in that is used to set it to true or false well in theory we could Define a different function here that we could invoke places that will set logged into false and clear the local storage then instead of using set logged in directly we can use that new function and down in our code wherever we invoke set logged in to false we could just invoke that other function so let's go do that let's head over to app.js in here we'll say something like function and we can give it a different name such as change logged in and then we'll take a value and basically what we're going to do is just set logged in for them passing in that value but this is going to allow us to do additional things so for example if value is equal to false meaning they're not logged in then all we really need to do is say local storage dot clear and that should remove any access or refresh tokens from local storage now keep in mind this is going to clear out all of local storage so if you're using it for something else such as dark mode you'll probably want to be more specific here and only clear out access and refresh tokens I'm not doing anything like that so I'm going to keep it as is now instead of passing set logged in you could pass in change logged in and let's try this out so we will log in and we will get local storage to see what's in there let's go ahead and change the access token so we can have an invalid access token setting equal to something like five access another protected route takes us back to the login and now let's go ahead and take a look at local storage and you can see that it is completely empty we no longer have the access token equal to 5 or the refresh token so it appears to have worked now you may be confused how we change the name here but throughout our application we are still using set logged in well the name that we pass in here is irrelevant because really what happens is when we import this we are giving it whatever name we want and we chose to give it set logged in so set logged in here actually refers back to this change logged in that we passed in so it's just uh different names kind of how arguments and parameters for functions don't necessarily have to be the same name so you could if you wanted to go through and change set logged in to change logged in throughout your application I'm totally fine with the way it is here there's only one other thing I can think of that we need to do and that is mobile which I definitely need to refactor the header so that we don't have to do this crap because right now this login button is not referring to the same login button that we custom defined earlier in this video so we have this turn area here but we have this additional setup down here for mobile you can see this nav link down here is doing the ternary stuff again so what I'm going to do is I'm going to just for now copy paste and take this whole ternary bring this down here and I'm going to paste but I'm going to replace the classes with the mobile classes and then we can remove this old nav link so I'm going to take that paste it here and same thing for right here okay now we will remove this old nav link and just make sure everything looks pretty much right and is working pretty much the same and we should be good to go in the next episode I want to take a look at the refresh token what that is and how it works and how we can use that in our application to keep users logged in for longer periods of time and potentially use it as a way to have a better default value for whether the user is logged in or not so stay tuned for that video be sure to subscribe and I'll see you in the next one [Music] hey everybody Welcome in this episode we're going to be talking about the refresh token we've worked with the access token over the last couple of videos this is basically how you prove that you've logged in and you have access to the site well this is going to expire fairly quickly and nobody wants to have to log in every couple of minutes for example now that time can be configured on the back end so it doesn't have to be a very short period of time but if it was the case that the access token expired every five minutes you would have to log in every five minutes on your application well typically applications are built so that you log in and you will stay logged in as long as you're on that website until you get off of that website in a certain period of time has elapsed this is what the refresh token allows you to do basically what's going to happen is the refresh token will give you a new access token every couple of minutes so you don't have to log in over and over and over again the refresh token is going to have a little bit longer lifetime let's go with the example of a day so as long as you visit the website within a day and get a new access token using your refresh token you will still be logged into the site if you wait too long well it's going to kick you out and you have to get a new access token and a new refresh token now anytime you use your refresh token to get a new access token it's also going to give you a new refresh token as well so basically if the refresh token say it lasts a day well that day period of time is going to refresh every single time that you use your refresh token so it's going to not expire until a day after your last moment of activity on that website so there's various ways you can do this I'm going to keep it pretty simple and just create a loop that's going to execute every couple of minutes to get a new access token and a new refresh token now there is debate on where to store refresh tokens storing tokens in browser local storage provides persistence across page refreshes and browser tabs however if malicious users manage to run JavaScript in the single page application using a cross-site scripting attack they could retrieve the token stored in local storage obviously the consequence of that is that they could use it to get a new access token if you're building some high Security application you might want to look into different options for storing the refresh token but a quick easy way around this is just to reduce the absolute token expiration time for the refresh tokens so that way you don't have a refresh token that just survives for say a week or two weeks instead you could make it expire after a few hours or a day this will reduce the total chance of something bad happening but you should still do the research on the different potential concerns and Alternatives this is just kind of your intro to get you started we're going to use local storage in this video because that's what we've been using and that's what is going to allow us to get this built the easiest then you could look into other storage options and really do you need to stay signed into a website for like a week in most scenarios at least in my experience it doesn't bother me that bad to have to log into a website every time I visit it and you know I might visit a website once or twice a day so if the refresh token expires after a couple of hours that's probably fine another quick thing to note is that in the back end software you can configure it to keep track of any invalidated tokens so you use a refresh token to get a new access token and refresh token and that one you use is no longer going to be valid this also helps reduce security problems because if that token has been out there exposed in some way and you manage to get a new access token and refresh token while any of your previous tokens are going to no longer be valid so in that situation you're going to have expired tokens by time and expired tokens by use let's run through a quick example of how this is going to work so you're going to make a post request to API token and you're going to get an access token and a refresh token you'll save both of these and the refresh token this is going to be used every so often to get a new access token so to do this you're going to use the API token refresh URL you're going to paste the refresh token you can see in our example it only gave us an access token and not a refresh token and this can work by default if you don't feel the need to refresh the refresh token however it can be configured in simple JWT inside of these settings rotate refresh token is defaulted to false so I think what we can do is we can make this dictionary and set rotate refresh tokens to true so let's go ahead and just try this so I'm going to take a simple JWT dictionary just to start and then I'll just get rid of these first two here I don't really know where to put this I'm just going to drop it somewhere and then I'll close this dictionary and we're going to delete these two this should be the default values so I don't think I need those in there and then I'm going to set this to true and now let's give this a shot we will head back over to token and we will log in grab a new refresh token just to be sure we're not getting anything weird and then I will visit API token refresh paste in my refresh token and we get a new refresh token and if you notice what this does end in a different value just to confirm that it is indeed a different refresh token so then you could basically refresh your access token and your previous refresh token however the refresh token we just had should still work to get even a new refresh token so that goes back to the settings here you can Blacklist after rotation set that to true and some of this is going to require some changes AKA migrations to the database so I'm not going to worry about that right now main thing I want to know is that we can use the refresh token to get a new access token and a new refresh token which we can just know that the previous refresh tokens can still be used until they expire which I believe is the default of one day another thing you should know is that this signing key comes from the secret key which is in our code somewhere so secret key right here this we checked into Version Control which you normally will not want to do however you can refresh the secret key we talk about this in a lot more detail in the back end course of mine however as this is a front-end course I want to worry too much about it until you are ready to go into production and at that situation you're going to want to remove the secret key as to not give people the ability to generate their own token means using this value if it's open source if you have a closed source application then yeah whatever it's not the end of the world all right so we got the back end figured out now let's worry about the front end I can think of two ways of doing this so we're going to do the first one but I'll share a second one with you so we're basically going to have a loop that will just execute every couple minutes to get a new access token and refresh token as long as this happens more often than the access token expires you should be good so assume your access token expires every five minutes you could have this Loop execute every three to four minutes that way we're always having a new access token and we don't have to worry about the user getting kicked off and having to log back in this seemed the easiest to me and that's what we're going to do the second option is to make requests like normal until you hit a 401 unauthorized meaning your access token has expired and that is when you will get a new access token with the refresh token then you will re-execute the original request so this is actually three requests the original which is 401 on unauthorized then getting a new access token and then repeating the original request and this will all be done automatically behind the scenes so it's not going to disrupt the user experience for the user and we're only making requests for new access tokens when we absolutely need to so let's get started with that first option which is the loop you can try the second one if you wish so here we are in our code and we have this saying our long-term goal is to use the refresh token well we're finally there so what we're going to do is we're going to have a use effect and this is how we're going to make that fetch now this is going to need to be imported from react so use effect and we've done use effects about a thousand times but this is going to take a function and this is going to have an empty dependency array so it executes only once the looping part is going to be done inside of here using a set interval and this is set up pretty similar to use effect where we pass in a function as an argument and the second argument here is going to be how how often this executes so we can just do something like 5000 this is in milliseconds so this is going to be five seconds now we're not going to want to leave this at five seconds when we're done but it's important for testing so that we can be sure this is working and now and here is where we're going to make the fetch so let's first Define the Euro and this is going to come from the base URL which we will import so import base URL from dot slash shared and this is really just the URL nothing crazy and now we will say Plus API slash token slash refresh so that's where we want to go and it looks like I need to import this with curly braces because it's not a default export so it'll look like this okay so now let's say fetch pass in the URL dot then this is going to take a function and we will have the response here and here we will return response.json and that's a function call and then another dot then this is going to have a function where the response.json will be stored in a variable called Data and we will console log data all right so that is our entire fetch hopefully that looks good except we're not quite done because we have to include the object which will have the method headers and body so we'll start with the method which is going to be post than the headers which is going to be an object and all this is going to have is content type being application slash Json and then lastly we will have the body this is going to be json.stringify and pass in an object here what's the body going to have the only thing we're going to need to include is the refresh token which is going to come from local storage dot refresh oh that was a lot all right so this is the entire fetch request but there's a lot here so let's just go test it out let's visit a page that doesn't require authorization and we'll take a look at the console we currently have something in local storage and it looks like we are getting a new refresh token but assume we didn't have something in local storage so we'll just say localstorage.clear you can see we're now getting a 400 bad request and the refresh field is required so you can take a look at any of these requests and you can see this so the payload is actually empty so we obviously don't want to have this problem so what we'll do is we'll check to see if we have a refresh token and we're going to do this inside of the loop here so if local storage dot refresh and then we'll just wrap everything inside of the curly braces and this is also really great because if the user intentionally logs out we will clear the refresh token and then we won't be executing this function over and over again so now it should only execute if we have a token which we currently do not so let's try it out we will log in hit log in and now we are getting what we expected in the terminal which is a new refresh token and you can see the last few characters here are changing each time so far we are golden what we do now is we just store that in local storage so we'll just go from data and say local storage dot access is data.access and local storage dot refresh is data dot refresh and we will no longer need this console log and then last thing you would just set this to a more appropriate amount you can calculate an amount out here if it's easier so let's go ahead and say const minutes and we're going to take a thousand milliseconds times 60 seconds per minute and what we'll actually do is just call this minute and down here we could just say a minute times five so minute times five or actually we'll probably want to do a couple minutes less a minute times three so I should execute every three minutes and it should already be the case that we are logged in for state but what the heck just to be on the safe side set logged in and I'm going to actually move this into then here let me set this to true now what I'm going to do is I'm just going to visit our site wait around make sure it works as expected and that I stay logged in but overall we should be good at this point all right there our refresh finally showed up here so a few changes I'm going to make is first I'm going to define a function and this will just be called refresh tokens and by defining this function I can invoke it immediately rather than having to wait for this time to elapse for the first invocation so I'm going to take all of the code that's defined inside of the set interval so all of this here cut this and move it into this refresh tokens function and now down here instead of having this inline function we can just call refresh tokens and I can call it once immediately right here by saying refresh tokens so now it'll be invoked immediately instead of waiting three minutes in this case last change I want to make is increasing the lifetime Early Access token from the backend settings I personally think the default of five minutes is a little aggressive but you can adjust it to whatever you like but inside of our simple JWT I'm going to add access token lifetime to 15 minutes and this is going to be imported so from date time import time Delta and now you can adjust the front end accordingly and I just think having a higher number here is going to reduce the chance of potential issues and if you're not on an app that needs Ultimate Security you could probably increase this number higher that's all I got in this video I'm sure there's lots of ways to do this so this might not be the most perfect way but at least get you going in the right direction and hopefully now you have a better understanding of access tokens and refresh tokens thank you for watching stay tuned for the next video I think we're going to be building our registration page so that'll pretty much conclude this last section of logging in and I'm really excited to see that so see you then hey everyone welcome in this episode we're going to learn how to register a user we already have the login capability and on the back end side of things this is made really easy with Django but registering a user is a little bit more complicated so we're going to build out the functionality to add another user to the user table we're going to start with the back end and then we're going to worry about the front end so here we are in the backend code and we're going to start with a URL so we are going to create a new path and this is going to be API register and this is going to hit views dot register and the name is going to be register so let's go ahead and build this view so that we don't get any errors down here so inside of our views we're just going to scroll down and create a new view we'll say def register and for now we will just say pass before we build out all of this code I want to talk about how we create a user and this has to do with the serializers we talk about this a lot more detail in our backend python course right now we have a customer serializer but we're going to go ahead and Define another serializer and that's going to be the user serializer which is also going to come from serializers.model serializer similarly here we're going to have an embedded meta class which will have the model the model we're going to use here though is already predefined so we'll import it similar to what we have here but the user model is defined elsewhere it's not something we created ourself so you can find it from django.contrib dot auth dot models import user so now we've defined that this is associated with that user model and then Fields you can just say all now we're going to also include a function in here that's called create and you'll want to make sure that this is in line with this class here so that it's defined in this one and not inside of this class since indentation is very important in Python so this is going to say self and then it's going to take validated data so you use self anytime we want to create an instance method and then we're going to define a user and we're going to create this from user.objects.create and pass in two name parameters here so username is going to be equal to validated data and we'll grab the username and then similarly we are going to do this again but this time it's going to be for the email so we will have email here so that is how we create the user object and then we say user.set password pass and validated data of password and then lastly we say user dot save in return the user so a little bit extra work but this is how we Define a custom create function which will be invoked when we create a user object now that we have this defined we should be able to First make sure we don't have any problems probably up if I had a comma here and now we can go in our views and Define the register function it's going to be pretty similar to how we create a customer so if you look up here where we have the post and we create a new customer using the serializer and pass in the data that's exactly what we're going to do but for a user model now so we will say serializer is an instance of user serializer we will import this from serializers so we'll say comma and then add user serializer and now that should be usable we'll check if it's valid so if serializer dot is valid then we'll say serializer dot save and lastly we'll just return our response and pass in status being assign the value status dot http 201 created now two other things we're going to need is we are going to need the request here and that will allow us to pass in to the data so the data is going to come from request.data so this will be passed in as the body and that's how we're going to create the user and then lastly for this to show up on the browser we'll say API View and pass in post now we should be able to visit API register and there's the option for post where you can create an object here so we'll just Define one real quick we will say email and that's going to be some email you can put yours in if you want I'm just going to say hello hello.com and then we'll have a username and this is going to be Caleb Curry you can't even spell my own name and then lastly we will have a password awesome I'm gonna copy this just in case we make a mistake and we need to do it again so hit post and it appears to have worked 201 created you should be able to go into the admin site so we'll go to slash admin go into users you can see the new user here Caleb Curry and I have a password so I know I went over all that really quick and didn't really explain a lot but again I don't want to focus too much on the back end here what you need to do now is we just want to build out essentially a login form but instead of going to the login API endpoint we're going to go to the register API endpoint and include the username email and password in the body so there is the potential for reuse of a component used for login and register but for now I'm just going to duplicate this so we will copy and then we will paste and we will rename this to register and then I'll just go in here and change some of these values so change this to register we're going to need some new state so we will have the username password and email and we'll make this a set email and now we can change the url we're sending this to so instead of API token it's API register method is going to be post and we're going to have headers but now we just need to modify the body so that's username password and now also the email this will need to come from a form input so let's go ahead and change our form so I will find one of these divs which describes the label and the input and I'm just going to copy paste and change the values to say email instead so this will say email here and then the four I'm also going to change the IDS so email and ID here will be email I think type you can even do email which will might give some front-end validation and changing the value here to email and then on change set email so lots of emails here make sure all those are updated hopefully I didn't forget any now let's see what happens when this form is submitted it goes to this login here you'll notice that we're trying to grab the access and refresh token as if we logged in so one option here is you could do the register and then inside of the final then if things were successful you can then do another request to have the user log in and then grab their access token refresh token that's pretty simple way without any modification on the back end an alternative it would be to actually return and access and refresh token on a successful register so that's going to require a back-end change so what we'll do is if the serializer is valid we will invoke serializer.save and before we return our response we will say refresh is refresh token dot for user and then we pass in a user how do I get an instance of that user well serializer.save will actually return that so what we can do is we could say user is assigned serializer.save and then pass in the user to refresh token.4 user this refresh token is going to need imported so I'm just going to go up to the top and say from rest framework simple JWT dot tokens import refresh token now last thing we are going to have a dictionary tokens and this is going to be assigned the refresh token which is going to come from a string representation of refresh what we just created and then lastly the access token which is going to come from a string representation of refresh dot access token so we have the tokens and we should be able to include that here so similar to how we passed in the customer to serializer data or down here the serializer data to customer we can do the same thing here where we just pass in the tokens one more thing we want to do is if the serializer is not valid we will return a response and in here we can put serializer dot errors and give back a status of status dot HTTP 400 bad request just like we did up here on line 44. since we changed this back end I want to test it out first let's go over to the register endpoint and we will just create a new object here you can type it out just make sure everything looks good and hit post and take a look at that we can access and a refresh token as a response this is amazing because this will magically just work with the code we have here I think so let's just uh give it a try so let's first create the paths for this so we'll need to go into app.js and we will create a new route path this time it's going to be slash register the component we're going to render is register this will need imported so let's go up to the top here and we'll import it right here import register from slash pages register so let's try this out make sure we can get it to look right so we will visit the register page so we're currently logged out and you might need to you know clean up the edge cases of like what happens if you're already logged in and all that but for now I'm logged out so it says login here let's just make an example of front end at front end.com front end and then front end we hit log in we're hitting at 404 and again I mess this up all the freaking time so just got to put a slash here I think you can make it so that with or without a slash will work but this will be fine we will know he'll log in and we're logged in the only suggestion to the UI that I would change is just changing that button from login to register so that way it looks correct and you can customize the functionality so for example we could make it so that we have a use effect that will log users out if they visit this page so that might look something like this and we'll just have an empty dependency right here local storage dot clear and then we also need to say set logged in to false to update the site state so let's test this out currently it says log out so if we visited the register page it'll log us out and then ask us to register an account so you can make the logic do whatever you want that's just an example of what you can do alright so there you go you got a pretty good summary of how to register accounts on the back end and on the front end at this point you have a pretty decent user system now you can build Upon This by doing email notifications for verifying an account user profile pages and customizing the display on the page depending on who is logged in so maybe you can only see certain customers or you can only do certain things so start researching and thinking how you could do this stuff and thank you so much for watching stay tuned for the upcoming episodes see you then peace out and definitely if you just could do anything for me or just love it if you could subscribe appreciate it foreign [Music] to a very cool and important episode in this series where we're going to be building a custom hook we've used hooks throughout our application so we've used use State use fetch use location use navigate well each one of these introduces some functionality into our application well if we ever have some functionality that we want to repeat throughout our application we can create our own hook in our case we're going to build a use fetch hook which is going to allow us to isolate all the fetching logic in one location and then anytime we need to get something from our API we can just use that hook and save like a gajillion lines of code so wherever you're making an API call such as in our example we have this definition page and we have a use effect and all this stuff here basically like 20 or more lines of code we can remove this all and introduce a custom hook that custom Hook is going to look something like this you could say const and let's say we have a variable called word since this is for a definition that's pretty much the same as the state we have here but we can now get this from our custom hook which we could call use fetch so use fetch we'll just get that word for us and then we can just use it throughout our application that will prevent us from having to write all this code over and over again for every single page that we need to get some data it's going to save a lot of problems then all we'll need to do is just take this URL and pass it in to use Fetch and we pretty much should be good to go to do this we're going to have to generalize a little bit because we're going to use this hook for multiple pages so when we Define it it's going to be pretty General so instead of talking about words and definitions we'll talk about data to create this hook we're going to create a new folder inside of source so we'll just call this hooks and I'm going to create a new hook called use fetch now I'm still following my Pascal case convention I started with the series but you can use whatever convention you want I would just say be sure to name it correctly here where we're going to say export default function use Fetch and I'm using camel case here now in here we can use any other hooks or react functionality so we will import use State and use effect from react and this is going to allow us to have our own state so const data and set data is going to be use State and then we will have a use effect this is going to actually invoke the fetch call now the actual URL to pass in is going to come from the parameter here so we'll say URL it'll be passed in as an argument when we invoke this so similar to right here use fetch we pass that data in that's going to be assigned to this parameter here and then we can just drop it down here like so and then we will get the response so response and we will say return response dot Json that also gives us a promise so dot then and in here we will just set data to the data that's going to come from response.json so set data data so this is a pretty familiar structure if you've been following this series so far now the next thing we need is an empty dependency array to make this execute only on initial load the final thing we need is a return in this case we can return data so after data is assigned a value it'll come back into definition and be assigned to this word here then we will be responsible to do any traversing that we were originally doing such as data of zero dot meanings we will do that in this file and we could do that down here right now by default this isn't going to work until we make those changes which I'm going to show you how to do in just a second but for now I'm just going to return a paragraph work in progress so this is because I want to focus first on just making sure we get the correct value over into this page so we need to import use fetch from and this is going to come from One Directory up inside of hooks use fetch perfect so we're not getting any errors in the terminal now over in the browser we can access a dictionary slash hello and it says work in progress which is what we were expecting we're not getting any errors yet so far so good what I want to do now is I want to create a use effect just to verify these values so this will be sure we're checking what the value is after the state is done loading so we'll say console log word now immediately word is not going to have a value but once that fetch is done it'll be assigned a value which contains the API response now we just need to adjust our traversal to grab the correct data and to do it optionally so that we don't end up throwing any exceptions so instead of returning work in progress we're going to say word question mark dot square bracket zero question mark dot so this is the syntax to say we want to grab the item with index 0 in the word array and if word doesn't exist return undefined and then do the same exact thing grab the meanings and if that doesn't exist on the item with the index 0 return undefined that way we're not going to get any exceptions instead nothing will be displayed on the page and then here we're going to do something similar where we say word index 0 dot meanings however we don't need to use a question mark because at this point inside of the ternary we are confident that meanings has a value so we'll save and we get the values displayed on the page so everything seems to be working as it was originally we can try it out dinosaur cool if you're confident now you can remove the values being printed to the console and you're good to go however it doesn't work too well if we get a 404 it just breaks so what we're going to talk about now is how we can build in error capabilities into our custom hook so let's go ahead and create a new state and it's going to be error status and set error status I'm using error status versus just error because I want to get this to be the status code whenever possible and this will come from use state so what we'll do is we'll check if there is not an OK response if this is the case we will throw response dot status this can then be caught after this final then inside of a catch so this will be a function which has an error parameter and we will just assign this to error status so set error status and passing e but in order to see this error on the outside we not only will return data but we will also return the error so error status inside of an array this will allow us to create two variables to store this information so not only will we have word but we will also have error status this is going to take the place of this error here and it will also serve the purpose of checking for a not found so we won't need either of those so when we save this we get an error and that is because we are now referring to these variables that don't exist I'm going to fix that in a moment but similar to what we did earlier I'm going to comment it out for a second and just console log this inside a use effect to make sure we're getting the right values so not only do we want to console log word but we also want to console log the error status and just make sure that we're getting that error on this page so when we visit a page that doesn't exist such as Texas we get word is undefined and the error status is the number 404 so it appears we're getting that value correctly so now if you want to take a stab at refactoring our code to work as it once did using this new error status go ahead and give it a shot otherwise let's just jump in what we will do is we will go down to where we had this if not found we're going to uncomment this section and instead of checking for not found we will check if the error status is equal to 404 so it's that simple of a change similarly for the error all we need to do is just check to see if error status exists so if it's defined and it's not 404 then something else went wrong so let's make sure that the 404 works it appears that it is and let's go ahead and switch our URL to just an empty string to simulate another error and in this situation it says there's a problem with the server try again later so it works as it once did and you can see our error status is not a number but rather a syntax error it doesn't really matter because we have a catch-all error and that's pretty much it at this point what you can do is you can remove the big comment we had from earlier and the use effect that was just console logging the data from our hook at this point our site works as it once did but our code and our definition page is much cleaner we can reuse this hook on other pages but that's actually what we're going to be doing in the next video we're going to stop here because we got it all working and you should have a pretty good understanding of how hooks work I do want to give a special thank you and shout out to another Creator who inspired me in this video and that is Pedro Tech who has a great video on a use fetch hook so if you want another perspective on how to do this thing you can check out his video the other fetches are a bit more complicated because we're dealing with access tokens and things like that so definitely stay tuned for the next videos where we're going to work on that thank you for watching and peace out [Music] hey everybody Welcome in this episode we're continuing from what we talked about in the previous episode where we created a use fetch hook this video we're going to be talking about how we can pass in a custom method header and body so basically we want to create this hook in a way that makes it more versatile so it can be used for more things so now we should be able to create data read data update data and delete data using this hook now there's going to be quite a bit of changes so we'll see how much we have done in this video we might move on to it part two after this we're just going to see pretty much what we need to do is we need to go through one of our existing components and try to replace all of the fetch calls with a call to our new hook so we're going to start with the customers page this has authorization and this has a fetch call to add a new customer so that will show an example of how we can use this hook for posting data and not just getting data so this is our hook here and we are returning the data and the error status so that we can display something such as a 404 on the calling Page by the end of this we're going to expand this to return more and we'll talk about better ways of calling it for now what we want to do is we want to go up here where we have the URL and I'm just going to take some extra arguments passed in so let's just go with a method headers and a body so there's plenty of ways to do this I'm just going to take them one after the other sequentially here and then what we can do is we can include that inside of a custom object here so where we would normally Define these we're just going to use the parameters so we'll just pretty much copy the names so method is going to be the method parameter the headers is going to be the headers parameter and the body is going to be the body parameter that will allow us to pass in custom values for each of these this means that use fetch can be useful for a lot more things such as passing in authorization tokens now anything that's going to be the same across our application we can leave inside of here so an example of this would be a 401 status code which would be unauthorized so if we check for that here then we don't have to do that in any of our individual pages so if response dot status is 401 then we can navigate to a login page pretty much anything we can leave inside of usefetch is something we're not going to have to repeat throughout our application and it'll save a lot of code and reduce bugs so now we can go into customers and we can try using this so here we have a use effect that is invoking fetch in passing in authorization and we have the navigate here we will want to include this previous URL state so let's go ahead and copy this here and bring it over to use fetch we'll just include that here and what we're going to do is we're going to just kind of build on this iteratively we will start with just checking that the redirect to login is working but in order to even do that we're going to have to invoke use fetch inside of our component so what I'll do is for now I'm going to comment out this entire use effect so we can reference it if we need for now and then what we can do is we can remove it later so I will save that and now let's call use fetch so first thing we're going to do is import it and here we will say use Fetch and this is going to come from one page up into hooks and then use fetch now that we have that imported I'm going to go below all of our constants and invoke use fetch now this is going to take a lot more now so not only will we have the URL but we're also going to have the method headers and body so what I'll do is I'm going to say const URL and Define it here which I'm just going to take from this line so not changing much so now we have the URL the method is going to be get which is the default so we didn't have that defined down here and then we will have the headers which is just going to be this object oh dang it I hate when it does that the scrolling on Visual Studio code in Mac is like way too sensitive I don't know if it's like that for Windows as well but anyways we're going to take the headers here and then lastly the body which we currently don't have one so we don't actually need to pass in anything for that if nothing is passed in it just won't be attached to that request now let's get the response from this we'll just say const result for now and then I'm going to console log the entire result so we'll say use effect and in here we will just say console.log result couple of issues here let's just go fix these real quick first thing is the way we are importing use fetch it is a default export so we'll get rid of these the curly braces there so that fix that error and now we just have to import navigate into use fetch so we will import that up here so we'll say import use navigate and we're also going to have use location from react router Dom and then let's make these constants so I'll say const navigate and this will be a call to use navigate and then similarly const location use location so far so good that should have fixed the problem so we can see our site now let's go over to the customers page and we're getting some errors so let's check those out in the console this is just from the display as we didn't change what was actually being displayed on the page so what I want to do is I just want to scroll down to where we have the return and just say return and leave a fragment here which will temporarily ignore this return so we're not going to get any errors displaying on the page we can now do a refresh here and check what data is being returned from the use fetch so we'll expand this the first item in here index 0 is an array the customers array the next thing in here is the error status which is currently undefined because we successfully got the customers so we don't have an error but you can see that over in use fetch where we return the error status here so far so good if in theory we logged out let's go ahead and log out it'll then bring us to the login page we hit login it takes us back to the customers page and we get that array so so far everything appears to be working now I want to talk about how we can improve the way we are returning and passing data so this is going to use destructuring and it's going to clean up our code a lot and make it more versatile so right now we're returning an array with data and error status well my preferred way of doing this is to return an object and if you ever do this where you trade the square brackets for these curly braces it's a shorthand way of having properties with the same name so it would look like this this would also work but since we just have redundant info here we can remove these and pass it back like this what this will do is we'll change the way inside of customers that we are retrieving those values so we can de-structure with curly braces and we can grab the data that's being returned and we can grab the error status we'll save and let's go ahead and change this console log to data and error status now let's check over in the console we're getting the same information the first thing data is being an object with one property customers which is an array and then we have undefined for the error status I prefer to use this object Syntax for returning as it reduces the chance of typing things out incorrectly because we actually have to match the names here so for example if I had this as data with two A's and then we said console log data with two A's well we're not going to get that information it's going to be undefined this is different than if we were using an array so if we go back to using the square brackets here and over inside of customers we replaced these curly braces with square brackets we'll save and check over on the site you can see we still get that information even though we changed the names of the variables over on this side and there's a higher chance of misalignment so for example if first let's change this back to data so everything is aligned if we decided to end up returning two things such as set data and then the error status well in our calling code we're taking data and then error status in a row this is naturally going to grab that second thing in the array so error status is actually going to be a function to set the data definitely not what we want so we can avoid that problem by using curly braces instead and over in the calling code using curly braces so now even though we've added that new thing here the set data our code works as it originally once did because we're using objects and property names instead of arrays which go off of position so basically the two long didn't watch version of that is just use objects when you can instead of arrays when you're passing values back and forth a similar thing can be done over in customers where we are passing all this data we're passing the URL the method and the headers we have that same potential issue of misalignment over in use fetch where we are taking all this information so instead we could pass an object and then we could just take the appropriate property names to avoid any issues then if the caller passes them in in a different order everything will work just fine so what we can do is we can accept an object as a parameter and D structure the three properties from that object called method headers and body so then we just expect a URL and then any other attributes you could of course combine those all into a single object however I think this structure is a little bit more fitting as it follows the same exact fetch structure you would expect so now over in customers what we'll do is we'll redefine this call as an object so we will surround the get and the headers and curly braces and we will give them property names so method is going to be get and then headers is going to be this object save that it'll reformat it this is what it looks like and we should be able to use the site the same way so we log in and we're getting the customers here inside of this customer's array alrighty our code is a lot better now we just have to worry about getting the information to display on the page which currently we have this older customers and set customers State well we can just use the state that comes from the use fetch so we will comment this out this is going to cause some issues Downstream where we are invoking the set state so I'm just going to comment out any other code that's using it for now we'll go back and worry about how we can add a new customer after we get the list of customers to be displayed so right now we'll get an error on the page because customers is not defined and I commented out the entire new customer function so why don't we just instead comment out the body of the function that way we don't break any of the wiring so we will comment out the content here and that way we get rid of that error now we just have to worry about the customers you could go in here and basically say data dot customers and then data.customers.map and you'll probably need optional chaining so you don't try to access a property on undefined and there we go we get all this junk up here and you can see I was doing some testing earlier so I have a bunch of crap in here I need to clean up this is pretty annoying though because basically we have to now prefix everything with data which gets pretty complicated and confusing so instead I want to figure out if there's a way we could basically do customers is data dot customers so I'm going to show you a way how we can do this and it's going to have to do with the restructuring you can actually jump into what is being returned so where we have this data here we could grab data.customers so the way to do this is you basically say you want data to be the source and you want this to go inside of a variable called customers this is going to be in curly braces to say that you want to access a property on data and then we can just replace our calls to data we're not going to use data anymore we'll just say customers similarly down here we can remove data and we don't have to do the long chaining now this isn't going to quite work we're pretty close but we're going to get a problem cannot read properties of undefined and that's because initially the values return from our use fetch are undefined until that fetch is complete an easy fix for this is to just go after this assignment here and say what's going to default to an empty object and this will prevent any attempts of accessing on an undefined now taking a look at our site this stuff pops up and everything is working next up I want to talk about adding a customer because it currently is not going to work so let's talk about how we can make a post in the next episode thank you so much for watching hopefully this video is helpful lots of information and syntactically pretty complicated so hopefully you're able to follow along stay tuned for the next episode if you want some more practice [Music] what is going on everybody in this episode we're going to deal with destructuring and default values because if you're not careful you can have runtime errors or exceptions thrown if you try to destructure a property that doesn't exist on an object this is happening in two locations in our code specifically in our use fetch custom hook we have these values here these are being destructured and they are expected to be passed in so what this means is a second argument is going to be passed in that is an object and it should have these three properties however if they are not passed in we will get a runtime error in the console it'll look something like this cannot destructure property method which is this first one here because the object that it's trying to destructure from is undefined that's one area of issue the other is how we are returning information so currently we have three properties data set data an error status and it's being returned in an object when you invoke this code you will need to make sure that you are doing it properly so that we are actually assigning to an object like so then we will need to make sure that these property values match correctly by naming them like so or renaming them to whatever you might want them to be so this is the proper way of assigning the return value and then here is where we would pass in that second argument so you could pass in an object here but if you don't pass in this object or if this object doesn't have those expected properties we still get that exception so the default is to go into where these parameters are defined and have an equals followed by empty curly braces and what this will do is assign an empty object if this object is undefined so what we can do is actually see this with a console log method headers body we'll save this and let's check out our site now we can see that it is working and we get three undefined so we no longer get that runtime error because it's going to assume that the value passed in is an empty object if it is undefined which in this case it is if instead it's not undefined and let's go ahead and pass in a second argument here well we're still going to get that same result basically the way the destructuring works is if the property doesn't exist on the object no exception is thrown and the value is just undefined so what that means is if we just passed in one of these properties let's go ahead and try it we could say method is get as an example now we should get get and then undefined undefined so the problem is not trying to destructure a property that doesn't exist that's okay you're just going to get undefined but no exceptions the real problem is when you try to destructure and the thing you're destructuring is undefined so if we say hey we want the default to be an empty object we're not going to get any exceptions thrown now there's another area where destructuring and default values can be important and that is to clean up our code if you look through where we are using our custom hook scrolling down into the display area we have a lot of traversing that's being done when you have a map that looks something like this where you have to jump down multiple layers this could be cleaned up we could just do this initially one time at the beginning of the code and then not have to do it every single time we want to reference those values you can take a look at the network request to see how the information is actually structured so let's go ahead and do a refresh here the search term is Hello this one is actually the page where you're on the request we are looking for is this one here and you can see how the information is structured so you can follow this structure to get the right information we will want to go through this structure near the beginning of our code and as we're doing this I'm going to console log what value we have so we will say use effect and in here we can just console log our state so console log and we're going to take a look at this word state so now when we take a look at the console we see this is what we're working with when we grab data from The Returned values so if we want to go a layer deeper we want to grab the thing with the index 0. what we can do is we can just use an array syntax like so and when we do this we're going to get an error because at the start it's undefined because use fetch doesn't return the values immediately so what we'll do is we will assign a default value of an empty array now it should work and you can see we're one layer deeper into that specific word now we can do the same thing this time we're with an object so we will grab the meanings property so to do that we will go into that object and grab meanings and this can be renamed to word similar thing this will throw an error because by default it is undefined so we're going to need to adjust the right hand side and just say that we want to have by default an empty array and then within that by default an empty object as we're one layer deeper and this syntax is not very intuitive this took me a lot of trial and error just to get right but at this point we should be in that deepest layer that we want where we have the different parts of speech so now that we have what we want we can adjust what is being used in the return so that we don't have to do all of this here so we'll just have word and word dot map and the page should look the same enter code would be a lot easier to work with if we needed to work with word a lot more now we can do is we can just clean up all of our console logs so we can get rid of this here and I think we had one inside of use fetch as well so we'll get rid of this console log and now our code is much more versatile we have the ability to pass in method headers and body and we are not punished if we decide to not pass that information in so everything seems to be good and we refresh we no longer get any errors in the console everything seems good we can test out a new word and it seems to work one stack Overflow question that helped me get to this conclusion with the proper nesting is this one nested object and array destructuring where they had a similar setup where they added some nested array and they go through some different options for grabbing specific things here is another good example where it shows how you can choose specific indexes or leave commas before and after to grab exactly what you want so I think some of these things could be combined to grab exactly what you're looking for that's all I got in this video thank you for watching in the next episode we're going to take a look at some of our other requests to make sure everything is working across our page so specifically we need to update our post requests to be able to add data to our web page stay tuned for that I'll see you then Welcome to The One and Only video number 53 maybe in this video we're going to be talking about how we can expand on our custom use fetch hook to now work with a post request which this is going to be a bit different because we don't want this to execute immediately on page or load instead we want it to execute when we click a button which is actually a little bit more complicated so there's probably a bunch of different ways of doing this I thought of one after doing some research I think this is probably one of the better ways of doing it but I'm sure there are others out there so if you have any suggestions drop them in the comment section below so let's just take a look at what we have and why this is not going to work with our current setup here we have our customers component and in here we are invoking our custom hook use fetch we're passing in the URL and anything else we want to be added to that request if you wanted to mimic this Behavior down on this button click below you can see we have this add customer component which is taking a a function called new customer taking a look at that code we have it commented out so you might think to copy this Behavior up here from our use Fetch and just modify it to instead of having a get method having a post method and this would allow us to add data we'll see what the problem is here shortly let's go ahead and replace this content with our use Fetch and without even changing anything we can take a look at the browser and you can see react hook use fetch is called and function new customer that is neither a react function component nor a custom react hook function essentially what this means is you're not allowed to do this the solution is to actually instead of having the use fetch return the data we can have it return a function which can then be invoked on button click so basically what we can do is we can create a function inside our use effect call it something like append data because this is going to add to state this is the function that's going to then be returned from usefetch so it's a little bit to wrap your mind around so let's just jump in and try to get something working and we'll just build as we go it might not be perfect from the start but by the end of this video we should have the ability to add customers to our list so what it's supposed to look like is you click the button a modal pops up you can type in data hit save and then that data automatically shows up on the page the ability to add that data to our state is still going to happen inside of our new customer function it's just going to look a little bit different instead of doing the use fetch here we're just going to invoke a function we'll just assume it's called append data and then going off of these parameters here we can describe what it's supposed to look like by creating an object name is name industry is industry so we get to this point and we have the object with a name and industry now we just have to Define this append data this is still going to come from use fetch which is here and you can see right now we're returning to customers and the error status this is now going to return a few other things so we're going to add request here this is going to be the original function to get the data so what we currently have and then we're also going to have the new append data so we will Define both the original request which we already have and use fetch here and the new append data as functions that will be returned from usefetch so let's go ahead and console log these values to see if we get anything on this page so we will have request and append data as well as the customers and the error status so now we have four things that we're going to get from usefetch I'll save and we'll do a bit of a reformat and the way we currently have use fetch is it'll execute what will be this request function immediately so if we take a look at the use fetch we have a use effect that just executes the fetch right away now instead of executing it right away we're not going to do that and instead we're going to Define this as a function so we'll say function request and this request function is going to execute the fetch so let's go ahead and close this function down below we'll get rid of the dependency array we're not going to need that and there we go so now we have a function that described the original behavior of our application and now we can define a second function to append data so let's go after this function here and we'll say function append data this will take the new data which is the object we passed in and we will Define the new fetch here however let's just take a break and Define a checkpoint with a console log and get everything wired up so let's just say inside append data and then we will have the new data here so now that we have these two functions we have append data and the original request we can return these from use fetch so here we're returning data and some other stuff we will return request append data and we're no longer going to return this set data because all that behavior is going to be done inside of this use fetch let's take a look at our site now you can see it's not loading our customers however we're not getting any major issues in the console in fact the function that's being returned is being displayed from that use effect so we have the first function which is request and then we have the second function which is append data this console log is coming from the customers page inside of this use effect request and append data so we've returned these functions but the request isn't actually being made and no customers are being displayed so before we go ahead and build the behavior to append data let's first fix the original functionality with this new structure all we really got to do is invoke that request function we just defined on page load so we will have a use effect with an empty dependency array and this will execute once on initial page load so here we are over in our code and we have this use effect to console log all of the state I'm going to keep that separate because that will show any state changes I'm going to have a new use effect here and this one's going to have the empty dependency array so it only executes once and now inside of here we can just invoke request this should do the trick so now when the page loads we'll invoke that function that comes from use Fetch and you can see all of our trash data shows up on the page so we've refactored our code it works the same way but now it's returning a function that can be called we can do the same exact thing on button click to invoke the new append data function so it should already be pretty much wired up because we have this new customer function being invoked which is invoking the append data function this will pass in this object here and it'll console log it right here so what that means is when we click add customer and then hit add again we get that in the console inside append data with the blank information we didn't type in here so far so good so the information is being received inside of append data now we just have to define the behavior to add to this list here so let's go back to our code and we will redefine this function so we'll say fetch this is still going to use the URL that's passed in all the way up here so we don't need to redefine with const and then we'll say dot then dot then and Dot catch so let's first work on this here where we're going to have another object defined here this will have method being post the headers being any headers that were passed in the body being Json Dot stringify and passing in this new data object this was passed in as an argument to this parameter here now we'll go to the next then here and first thing I'm going to do is I'm going to check for the response code so if response dot status is 401 then what we're going to do is navigate to login and this is going to look very similar to what we have up here so copy this and we'll just replace what we have down here paste and now what we will do is we will add a general catch all so if a response is not okay we will throw the response dot status and that's going to go to set error status so we'll just do the catch right here real quick so we will Define it as e and for now we can console log it just so we can see that easily go on slog e set error status to E all right so that's good now let's figure out what happens if everything actually is working so if we get to this point we can return response.json which will then come down here to this then and I'm going to say data but then I realize you know this state is called Data so I'm actually going to rename this parameter to just D and we'll just make a checkpoint in console log D and I'm just going to say in the then just so we can find this easily all right so let's see what happens we'll save and let's run so let's go ahead and type something in here Google Computing we'll hit add so it returns an object with a property customer going into this you can see that item here so basically we want to take this object and append it to this list of data now I am really designing this with the customers page in mind however it's pretty General at this point we haven't mentioned customers inside of our use fetch so let's try to keep it General and not actually say hey let's navigate into the customer property as then this is only going to be useful for customer data so if you want to repeat this Behavior with some other page well it's not going to work as well because you're going to be using the wrong property names so instead what we could do is we could just grab the property without using its name so we could just say hey let's grab whatever this is whatever it might be called the way you can do that is by saying object dot values pass in the object and grab the property with index 0. so just save that let's try it again Google Computing hit enter and now we just have the object without the property this is what we can use to append to the list in the state so let's just take a quick moment to look at the state as it is we'll console log it and see how we can append this object to the state so what we're going to do is instead of just console logging this new data I actually want to console log data which is the state so when we submit another value this is the data that's submitted but our state is not actually an array it's an object with a property that is an array and that's the way it's returned from the API and use fetch doesn't do anything to remove that property so you could modify the way the state is being stored to stored as an array instead of an object with an array in it but this is basically a similar problem where we can't just push this object into the state because the state is not an array it's an object so instead we want to grab the array of data without using the property name so that it can stay General so thinking generally is pretty complicated we pretty much want to say hey take this object and add it to the array that's inside of whatever the property is called without actually saying that property name so we're going to do something very similar as to what we did here we did object dot values passing in the new data we're going to do that same thing for the existing data so what we would do is say object dot values pass in data which is our state grab that array and say push passing in this here so just for Simplicity let's go ahead and assign it to a variable we'll say const submitted so this is the new data and this is going to be object dot values d index 0. and now we can replace any of these lines with submitted similarly here we're going to pass in submitted so this should push that new object into that array but if you remember that we've talked about before you're not supposed to modify the state directly you always use set state so how can we do the same exact Behavior but inside of a set data instead of using push well I personally think the easiest way of doing this is to actually create a new object so we'll say const New State this is going to take all of the properties from the current state and then what we can do is we could append to that new state instead of the actual state since new state is just a normal variable it's totally fine to push the data onto it then all you have to do is say set data and pass in the new state so this is really complicated so let's just test it out on the site so let's just do a refresh and let's go ahead and add a customer and this time we will go with Uber and the industry is going to be ride sharing we hit add you can see that data shows up in the list immediately without a page refresh now we will have to have it so that this closes on a success but let's just go through this code one more time since it's a little bit complicated first thing is we grab the object that is being added to the array we duplicate the existing state which is going to be a new object in memory and then we push the new object onto that new state and we replace the existing state with that new object now because this is a new object it's seen as a state change if you were just changing the properties of an object and one of those properties there's an array the actual object reference where it is in memory wouldn't change so it wouldn't be seen as a state change this is what causes the page to re-render and the data to show up on our page immediately last thing we need to do is just make this go away so let's go ahead and remove these console logs and see if there's any other ones I want to get rid of I'll keep the catch there for now uh we'll save let's go back to the customers and we'll just check to see if there's an error so if there's no error status then we will toggle show so let's test it out tests testing hit enter it shows up and the modal goes away now you can just clean up all your console logs so you're not polluting the console with a bunch of garbage so let's go up and just comment this console log out or just comment this whole use effect out and this old use effect we're not going to need that anymore so I'm just going to delete that so basically what we're doing is we're building a library of functionality that we can use for multiple Pages or multiple applications but it's complicated so you have to probably try this out with some other pages and make sure that it's General enough to work with other types of data and you can customize this however you need there's still the possibility to expand on this to do deleting and updating data you know probably various other things as well like logging in or whatever it may be but I decided I'm just going to end it there and leave that to you if you want to continue building on this use fetch you can as some practice but what we're going to do is we're just going to end there and leave all the other fetches as they are since our application is working but there's one thing that we did break and that is the definition search which was using usefetch as well so now when you search a term it just doesn't work so if you want to refactor our definition real quick we'll go into definition we will first alter what things we care about specifically we want the request function and now let's create a use effect that'll just execute that for us since we don't have a button we'll say request and now it works so very little refactoring needed in our other pages so this video is kind of insane and it's totally okay if you didn't memorize a hundred percent of that go through it again if you wish if you ever feel like you might want to build this use fetch library of functionality then you'll probably want to understand this code fairly well writing code in a general way is difficult and wouldn't be surprised if there's some bugs in the code Row in this video so don't trust it with your life definitely test it out and see what you can do if you want to support this channel be sure to subscribe and check out that next video peace out [Music] welcome everybody in this episode we are starting something completely new because what we were working on before honestly was just really boring and I was just absolutely tired of working on it my soul was dying a little bit inside and I was withering away rather quickly so this episode we're going to start with a completely new app and this time we're going to be adding two interesting things which is typescript and axios for our requests so we're basically restarting so some of this may be some review getting things up and going but if you want some more practice this is a great place to start so this episode we're going to talk about how to start a typescript react project and you might be wondering what is typescript is this like a new language is this an alternative to JavaScript well it's very similar to JavaScript but it adds static typing so our variables are going to have types this will help prevent run time errors during the execution of the software by moving the those errors to compile time errors definitely pros and cons to this it's going to take a little bit extra learning and a little bit extra work up front but ideally the execution of your code goes a lot better because you don't have to worry about as many runtime issues all right so we're going to talk about how to create a react application starting with typescript if you already have a react application it is possible to add typescript in after it's already been created however it's easiest just to start with typescript so here's documentation from create reactapp.dev here's how you can start an application with typescript or instructions to add typescript to an existing create react app project so we're going to go with the first one here you can copy if you have this page open or you can just type it out and what we'll do is go to a terminal and you'll want to change directory to wherever you want to create a project so I'm just going to go into my CS folder which is where I put all my code and then I'll say npx create react app and then go ahead and give this some sweet name so we're going to build a little application to check crypto prices so I'm just going to call this crypto alright so I guess you can't name it whatever you want so let's go ahead and change this to something like crypto currencies let's just go through the process of creating the app and I think you'll find that it's pretty similar to create react app if you've used it without typescript there's just going to be a few things different so let's go ahead and say code cryptocurrencies and that'll open that project in Visual Studio code or just open vs code and open a folder finding this one so pretty similar structure you'll notice a couple of differences such as this react app environment D which brings some react script stuff in I don't even know what this file is for to be honest but it doesn't matter we're going to go ahead and delete some of these other things we don't need so we're not going to do any testing so we'll remove those we'll remove app.test we will remove the logo you'll likely notice they have this tsconfig.json file which is where you can configure your typescript rules we're going to keep that and you'll notice that the JavaScript files now and in TSX so let's go ahead and go into the CSS files and clear those out and now let's start in app.tsx we will remove the logo and inside of index.tsx we will remove the report web vitals and remove this section down here I think that's all that we need to remove from index.tsx now we can just go into app.tsx and remove everything inside of this div so we will just say hello and let's run this application make sure everything is saved and we'll open a new terminal and inside here we'll just say npm start now you may have your other application running still so you can see it asks if you want to run on another port instead that's up to you so if you don't then you can go close out of your other server I'll close out of that and now we can restart when the page loads it'll look something like this so now you have a typescript application going now the other thing we're going to be using is axios which is another way to make requests so pretty similar to fetch but slightly different and a little bit cleaner in my opinion just want to get experience with another option if you're already familiar with fetch switching over to axios is going to be really easy actually probably easier than fetch so for this we will want to install axios so it's not included by default so let's go ahead and say npm install axios once this is done you will import it you'll say import axios and this is the default export so you're not going to have it inside of curly braces you'll say import axios from and then inside of quotes you'll say axios let's jump into using axios by making a request to an API we want to use an API that doesn't require any kind of key just to keep things really simple I was looking around for a good cryptocurrency API there are a lot out there the one I think is going to work best for this series is coin gecko so coin gecko is a really popular website to look at coin prices over time very similar to coin market cap so we can get a lot of this information displayed on their page inside of our application by using their API and they have a free one that at the time of this video does not require an API key and if they change that well I'm going to throw hands so don't ruin my series coin gecko in fact you should sponsor me everybody needs to know about coin gecko anyways you can get documentation on their API at coinggeco.com English API documentation and they have some examples down here so let's go with this here you can try it out and you'll just throw in an ID the IDS come from coins list but for example I know Bitcoin should work and then you compare that to some other currency such as USD the other stuff is optional so we'll execute and you can see Bitcoin is priced at 20 167. so overall using this API is easy and then you're given this URL that you can just copy and paste in a new tab and you'll get that data so this is exactly how you're going to consume this API no keys required although I want to do more than just get the price of Bitcoin so let's see what other options are available to us scrolling through we could get a list of coins let's try this out okay and we will throw in actually you don't even have to pass anything in here really easy I'm gonna die of old age waiting for it to load though all right this one's just broken I don't know let's try the next one so get oh oh my gosh let's try this again you know maybe I don't want them to sponsor me let's try this one all right we'll go in here and we will try it out the verse currency we will put USD and that's the only thing required so hit execute now do note this may require paging if you want to get all of the data right now we're just getting 100 of them but this is the URL we can use to get all the data we need so let's take a look at what it might look like you can scroll through here lots of stuff so each thing will have an ID a symbol and then a bunch of information about it and basically we could load this into a drop down allowing the user to select a specific cryptocurrency and then we can load some data about it so let's talk about how we can do this inside of our code so make sure you grab the URL which I just realized you could just take this one here instead of selecting it inside of the curl but yeah grab this request URL they should add a copy button anywho we're going to take this and we're going to say const URL and assign this that value now this is a string normally we wouldn't have to worry about the types too much but we need to pay a little extra attention when we're using typescript however we're not getting any problems with this either and that's because the type is inferred from the value we're assigning to the variable if you come from other programming languages you might be familiar with something like VAR URL without giving it a type and then you put some value here as opposed to doing something like string URL it's a similar concept here where the type is automatically decided for URL because of what we assigned to it and that's all done at compile time because typescript is compiled down to regular JavaScript we can see this easily by changing this to something else say let and then saying let me clean this up URL is five this is our first typescript error and you're going to see it show up in the problems tab down here so type number is not assignable to type string and this is a typescript error if we weren't using typescript this wouldn't be a problem you might be curious why this is a benefit well if we design our functions and our code to accept certain types we have more predictable Behavior so for example we want to add some data together well we would want that to be a number and not a string and if we tried to use a string we could have a compile time error so let's go ahead and change this back to what we had we will set this to const now I've just been kind of showing some of the typescript basics here but let's actually try to make this a working page so we'll go ahead and switch these around so that the return is at the bottom and our web request is going to be made inside of a use effect so let's say use effect and this will take a function which is where we're going to Define this URL so I'll take that from there paste it in the use effect and then we will import use effect so import use effect from react and I'm going to remove this other import that we're not using right now and we'll keep axios there because we're about to use it so bring this down to the next line and we are going to say axios dot get pass in the URL pretty similar to fetch we are going to have a then which is going to have the response here the primary difference is that we do not need to say return response dot Json and then have another then like we would with a fetch instead we can just have response dot data so response.data is going to have the actual data from the request so to see this we can say console.logresponse.data and to get this to only execute once on initial page load we will put an empty dependency array so this is what our axios request is going to look like so let's try it out we'll visit the page head over to our app and open the terminal we should in theory see an array of 100 elements so we're able to get that page and this is a bit simpler than a typical fetch that we would have done in earlier on in the series so I like the way this is going looking pretty clean so now what I want to do instead of console logging response.data I want to assign this to some state so let's create some State up here we will import use State and inside of app we will say const kryptos set cryptos and this is going to be assigned use State and then let's set cryptos down here so instead of console log we will invoke set cryptos now down here in our return we can print that information on the page for now so to do this what we will do is first create a ternary so if kryptos has a value what we're going to do is do kryptos.map to Loop through the data if there is no data then we will just return null now we're getting our error down here property map does not exist on type never so to fix this we can say that the data being returned from this API which looks like this should match some structure we defined in our code what this will look like is defining a type up here so we can say export type and we will just call it crypto here with a Capital C and we will Define what the properties expected on this type are so we can look through this list and just grab a few things we're interested in let's grab the ID the symbol the name not too interested in the image maybe just like the all-time high and the all-time low and the price probably the name to be displayed so what you can do is you can copy these from the response or you can type them out if you want this is just a way to make sure we get the exact property names and we'll save it'll kind of format that a bit but instead of having actual values we're going to replace these values with what type they are so this is a number and for simplicity's sake I'm really not interested in a lot of these things so I'm going to get rid of these if you're following along you could definitely keep these but I don't plan on using them so I'm just not going to have them on here and that'll just keep our code a little simpler so this is a number the current price is also a number the ID however is not a number instead it is a string so we'll say string yeah and you can just keep whatever excites you out of this list again the name is a string here the symbol is a string and that looks good to me I think actually I'm going to add two back in that I decided I wanted which was high 24 hour which was a number and low 24 hour which was a number so now that we have this type we can say that the state should be of this type but not just a single crypto It's actually an array so to do this what we're going to do is after the use State before the parentheses you're going to use less than and greater than angle brackets here and you're going to say crypto is the type and then use square brackets to say that it's an array and then you can use the pipe or the or symbol or the union symbol and say null so this can either be null if we don't have any returned or it's going to be an array of crypto and now that we told it what type to expect we no longer get that same error but we're getting a new error here so you can see typescript is really guiding us on what to do next this is expecting one to two argument minutes but got zero so the argument it is expecting is a function and inside of here we will need to do something to show up on the page because we are assigning to type react node so for now we can just return a paragraph and using curly braces we can grab a single crypto object we'll just use the lowercase C here crypto and we can type out crypto Dot and you can see all these properties that we've typed out up here are showing up in the intellisense so we can be sure that we don't mistype something so let's just go with the name and if you mistyped it say you put name with two e's you're going to get a typescript error so you never have to worry about using a property that doesn't exist on that type so let's switch that back to name and let's also add in the price here so we will add in a space and then a dollar sign plus crypto dot current price so saving that we'll do a quick reformat this is what your code should look like we don't have any typescript problems and checking out the page we see all the cryptocurrencies and their price another really valuable thing provided by typescript is it will prevent you from using some data that might not have a value I was already ready for this using this ternary but let's say we got rid of this ternary and we just put these curly braces down here getting rid of that as well well this is going to give a problem saying object is possibly null or undefined so we actually won't even be able to use this code we're going to get an error in the browser you may also notice typescript is pretty clear about the difference between null and undefined those are not the same thing in JavaScript just so you are aware undefined is when a variable has no value where null is a value that value is just nothing so you can see that specifically here where we say this could be an array of crypto or null but the default here is actually no value at all which is undefined so if we defaulted this to null Now it only says object is possibly null it still doesn't fix this problem down here so we will go ahead and add that ternary back in kryptos and null all right so far so good what we're going to do is we are going to add all this to a new commit and I'm just going to call this commit initial API request with axios and type script and up in GitHub I'm going to call this repo TX axios and I will make this public so you can reference this code so we'll create this repo and then I will push my repo up to this location and now you should be able to get this code here and you can go to the commit history to find any of the commits viewing the code at that time if you need to reference anything thank you for watching my intro to typescript and axios hopefully this was helpful and in the next video I'm hoping to build upon this up next I want to create a component inside of typescript so we have to worry a bit about types and it'll be pretty fun so check it out I'll see you in the next episode be sure to subscribe [Music] hey everybody Welcome to episode 2 in the typescript miniseries in this react Series in this episode we're going to learn how to create a component with typescript so basically we're going to learn how to set the parameters that are expected to certain types and you can also set the return to a certain type if you wish I'm kind of following this documentation here so this is the react typescript cheat sheet and they'll have examples of function components as well as hooks so you've seen similar Behavior to this in the previous episode now we're going to worry about creating our first component so let's head over to our code this is what we have currently and for each one of these cryptocurrencies we are just displaying the name and the cryptocurrency price it might be the case that you want to do something more with each of these cryptocurrencies and you can think of each one displayed on the page as its own component this could be a component and then we would basically re-render that same component passing in new data each time yeah it's pretty simple right now so to doing it all in line is probably okay however as we add more we probably want to organize our code and components so let's go ahead and add a component so inside a source we will say new folder components and inside of here we will create a new file and we'll just call this crypto summary so basically just a summary of that crypto and this will end in TSX now inside of here we're just going to say export default function crypto summary and I went with crypto summary because back in our original code I just had a little too many crypto and cryptos and all these different variations of the same word so crypto summary was a little clearer to me here and I'm just going to first Define this as we would normally Define a component and what we'll do is we'll take this line of code and that's what we will display inside of this component so we'll bring that over here and say return and paste that here now the actual cryptocurrency would come from props so you would say props Dot crypto.name and props.crypto.currentprice so this isn't going to work quite out of the box as you can see we have some errors floating around but let's first piece everything together so back in our app we are going to render crypto summary and we will pass in the crypto as the crypto prop so crypto inside of curly braces right here close that and then we'll just need to return this so we'll say return and that'll fix most of the errors here now we just have one problem back in crypto summary which you can see is parameter props implicitly has in any type so what you can do as a quick fix for any of these is you can put a colon any and that'll basically say hey we're going to accept anything as props here but that kind of defeats the purpose of typescript remember the whole point is to statically type our variables so we can avoid runtime errors so if we just use the keyword any we might as well not be using typescript but just letting you know that is a possibility if you just run into an issue and you just can't quite figure out what's going on with the typescript syntax you can just say any however what I want to do is I actually want to type this so we know exactly what to expect for this function what we can do is instead of getting props of type any we can actually destructure which will basically simplify our code because instead of grabbing props we can just grab the crypto object and then remove the props throughout our code so by grabbing that crypto property we're able to reduce the amount of code we have to type throughout our entire component we actually haven't changed anything because this is still typed to any so we don't have any of the static typing instead what we can do is we can describe a new type and we could call it app props for example so let's go ahead and create this type it's going to be defined up here we'll say export type app props and this is going to have a very similar structure to what we did up here for a specific crypto we will just Define what we expect the one thing we expect is a crypto object but what exactly is the type of this do we put object no not quite because this is actually an object of type crypto so this is the thing that we are passing into this crypto prop so what that means is we can actually use this type over here for the type here crypto which in this file doesn't exist so we need to import it in order to get rid of these different issues so we'll say import crypto from dot dot slash app so that brings the crypto type into scope in this file which we can then say the crypto property is going to be of that type and we can destructure to get that exact property and then use it throughout our code now the return type for a function you can put after a colon here what exactly are we returning right now it is known as jsx dot element so when we add that it works exactly the same way but now if say we forgot to return a jsx element you know if we said no return at all well that's going to be a problem but more likely you know if we return something that wasn't of type jsx element it's going to say type number is not assignable to type element so it basically looks at this and then looks at what is expected to be returned and says uh oh these aren't the same type you're dumb you should fix that I don't really find this return type for a component to be that helpful but you can put it there if you want so the way we've been doing this now we've been defining these different types inline if you wanted you could Define a new folder inside of source and call it types and let's just try the example of the crypto type and this is also going to need to be a TSX file so TSX let's go ahead and bring this type over to that file so we'll paste that here and now we can change our Imports so we're going to need crypto over here so we'll say import and we will say crypto from dot slash types slash crypto that should get app.tsx working and then similarly we're going to do the same thing in the crypto summary so instead of import crypto from App we're going to import from dot dot slash types slash crypto and that'll work now for the app props well this is specific to this component so I think it'd be appropriate to leave it right here however since you know there's a good chance you're going to be using this crypto type throughout your application it makes sense to put it in its own file an alternative setup if you want to just have all your types in a single file you could actually just rename this to something like types and then you would basically import that crypto from types but then you could include multiple things here so crypto and whatever other types you define they could all be defined in a single types file however way you want to do it should work as long as you are consistent and in this situation you probably wouldn't even need to put it in a subdirectory so you just put it in source and I know I'm screwing everything up but this might be a better setup if you just want all your types in a single file then you don't have as many files to worry about so let's save all this and make sure our application is working the way we expect and there you go seems to be good you can now get rid of this directory and Define all of your types inside of types.tsx so just to summarize what I was saying there you have really three different options you can create types inline whenever you just need to define those such as how we had it where we had that crypto defined inside of app.tsx or you could create a directory that has all the types and Define each type in a new file or the third option is just to create a types file which has all of the types defined in there which way you want to do it does not really matter just be consistent across your application and if you're working with other people make sure everybody's doing it the same way now another question you might have is what about interfaces you know maybe you've seen typescript a bit before and you've seen the word interface being used versus the word type well going off of this cheat sheet there are both types and interfaces and the general rule is to use interfaces until you need types but it says consider using type for your react component props and state for consistency and because it is more constrained so that was kind of my justification for using type however you can use interface as well and here are some of the differences so now what I want to do is have a drop down instead of listing everything out on the page just have a drop down where you can click choose which cryptocurrency you want and then that information pops up that's what we're going to be building in the next video so stay tuned and I will see you in the next one foreign [Music] we are going to be creating a drop down in react so the content of that drop down is going to be loaded from an API and then when you select something we're going to have stuff show up in the page this is a great way to condense the size of your page but still have the same amount of information right now we have everything just barfed on the page here but if you could just select one to get the price well then this entire thing could be condensed to the size of this little section right here versus a never-ending scrolling page so I just committed crypto summary component if you want to get the code at where it is currently located and that was a weird way to say that but you get what I'm saying so let's go ahead and create a drop down so instead of rendering the actual crypto summary for each crypto we will render a drop down list item which is actually surprisingly easy if we will create an option and this is going to have the crypto name displayed right here so crypto dot name and then all we have to do is return to get rid of all these errors all right so let's see what that looks like uh it's not working now all of these options that we're going to be able to choose from need to go inside of a select so we'll create a select right here and then we'll take the closing tag and move that to after the loop so we only have one of the select tags the open and close and then we'll Loop inside to create a bunch of options this will give us a drop down with all of the different cryptocurrencies pretty cool not gonna lie so now we have to figure out which one we have selected so when we select something how do we get information to pop up well for the option we're going to have a key and a value so we'll say key and value and we will use the ID for both of these so crypto dot ID and crypto.id so the key here is actually for react so if we remove that and take a look at the console warning each child in a list should have a unique key prop so that's what that key is for the value on the other hand is to decide which one was clicked this allows us to get the target value inside of an on change so I'm on change and this is going to be a function with the event being passed in so we'll create a parameter there and let's just console log e.target.value so let's see we will select one of these and we can see the value in the console so for each one of the options we've added a value attribute and this is what is used for e.target.value inside of the on change event handler what happens if you don't put that value I was initially confused by this because I would go in and remove value and when I selected one of these it still appeared to work so for example I would click one of these and it would say Tara Luna classic but the important thing to know is that each option element should have a value attribute containing the data value to submit to the server when that option is selected if no value attribute is included the value defaults to the text contained inside the element so this is really using crypto.name instead of crypto.id so what that means if if we put back the value and try this again we can still select the same one Terra Luna classic and get something in the console but this time it's Terra Luna which is the ID for that cryptocurrency so subtle thing but you should just know that it's probably important to have that value there because the ID is a better way to identify one of these cryptocurrencies now inside of our code instead of console logging here what we can do is we can actually find that ID inside of the array and display the extra information so what we can do is we can say kryptos which is our state DOT find and you can see this automatically uses optional chaining and this is going to take a function where the property here we'll just call it X is each one of the cryptos as it Loops through these and we will just return true if the ID is equal to e.target.value which we will get from E there so to do that we can actually remove these curly braces and just check if x dot ID is equal to e.target dot value if these return true it'll return that element from the array which we can then assign to some variables so we'll just say const c and then what we can do is we'll console log C just to see that it's still working so let's try it we will refresh we'll select one of these and we get that object so that's how we can go from an ID to an entire object now what we can do is we can just display this information on the page I think the easiest way to do that is to have a selected state so what we'll do is we will create a new state up here const selected and set selected and this is going to be use State what type is this going to be well instead of an array of crypto like we've done up here it's just going to be a single crypto so it'll look pretty similar we'll say crypto or null and we will default to null and that should do the trick and now we can set selected down in our event handler so instead of console log C we'll say set selected and pass in C now we can refer to the state down below we have one problem argument of type crypto or undefined is not assignable to parameters of type set State action crypto or null the easiest fix for this is just to allow an undefined so instead of defaulting to null we can just empty that and that works just the same now we have selected so we should be able to render this down below so after this select div we will just render a crypto summary and pass in the crypto that's selected as the crypto prop so we'll say selected and then close that now I must have one parent element so let's go ahead and Surround this entire thing in a fragment so open it there and then close it all the way down below after the crypto summary now we will need to do some conditional rendering here to fix this problem because we won't want to do this if we don't have a selected crypto so we will just say selected with question mark and if not we will just return null we'll save that and now let's try out our application we'll click the drop down select one and the value shows up one other quick change I want to make is to have a default value there that is not a cryptocurrency but rather a general message like choose an option to do this you will create another select option which will say whatever you want and then you have to just set that as the default so to create that option we're going to place it here so inside of the select but not inside of the loop we only want one of these and we're going to say option choose an option so we can check this out and you'll see that it is the default here since it's the first one there however just to be completely proper let's just say as an example this came after the loop well now it's still going to say Bitcoin and we're going to have choose an option down here at the bottom so if you really do want to tell the select that this is the default what you can do is give this a value and we'll just call it something like default and then inside of the select we can create a new attribute default value and we will say default so now in theory this should work the same when it's at the top and if we move it down to the bottom it should still be the default yes there it is I was like oh no it's not working I just had to do a quick refresh so there is how you choose a default message for it to be displayed to the user and if you want you can go through a little of extra effort to figure out how to choose a certain cryptocurrency by default and display that information on the page that's up to you that's all I got for the drop down in this video but wouldn't it be cool if instead of just having a crypto price show up we had like a chart that showed the price over time well wouldn't it be awesome if that's what we were covering in the next video guess we'll just have to find out might not do that so thank you for watching hopefully this video was helpful and check out the next video where we're going to do something cool I'm assuming so see you then and be sure to subscribe [Music] in this episode we're going to take a look at displaying a price history chart for a selected cryptocurrency a quick preview of something we can build is this here where you select the cryptocurrency it'll display a chart and then you have the option of changing what range of data you would like this first video we're going to focus on being able to select a cryptocurrency and having the chart show up in the next video we're going to focus on this drop down so let's get started we already have the functionality for selecting the different cryptocurrencies so all we have to do is make another request to get historical data and figure out how to display that in the chart there is this package chart JS which will make this pretty easy for us and there is a wrapper to this called react charge as2 which we are going to use so we'll just need to install chart.js and react charge as2 so let's head over into our code and in the terminal we will say npm install chart.js and react Dash chart js-2 now there are good usage examples with react chart JS so if you go to their examples page we're going to be using a line chart and they will have some code that you can import and a quick example which looks very similar to what we are trying to do so we will copy over these Imports and then they have these options here these will describe general things such as what shows up here and where the legend should be Etc then we have the labels this is what shows up down here for our use case this is going to be replaced with dates or times and scrolling down some more we have this data sets this is where we actually pass in the data they're displaying two lines here but the actual data will be passed in to this data property here they're using some fake data for us we are going to pass in the cryptocurrency prices at those times then what we'll do is we'll just use state for this data and for these options so changing any of the values will re-render the content on the page so let's first grab all of these Imports so everything from here up so copy that and we will bring that over into our code we're not going to use the fake data so we can just remove that and we can remove any other unneeded Imports now we're going to have two new state variables so const data that's what is going to be passed in for creating the line and set data and then we'll have const options and set options so we created some new state but what type are they if we're using typescript we want to take advantage of any static typing we can get and fortunately charges does have some typescript support if you're watching this video for the charts and you're not using typescript that's fine you can follow along still you just won't need to do this part so actually it's react chart js2 that has some typescript types we can import so we will take this line here so import type chart data and chart options from chart.js this will allow us to type each one of our state variables so we'll go back over into our code and we'll import that here and now we can Define the types for our state so we use angle brackets this is going to be of type chart data and this one will be of type chart options now one thing you'll notice is that these are actually generic types where you're going to pass in a value inside of these angle brackets for that type so we're actually going to have two sets of angle brackets so we'll have chart data and then less than greater than and we will pass in line which is the type of chart that we want to display similarly we're going to do the same thing for chart options passing in line you can modify these for whatever chart type you're trying to display here but line is good for us and what we'll do now is go down and try to render a line chart so we will just say line options being options and data being data it's that simple but one thing we have to do is say hey if data does not have a value don't display this at all because then we don't actually have anything to display so what we'll do is we'll say data then display that otherwise no and we'll surround this entire thing inside of curly braces like so so data is going to be filled in from a request to an API whereas options we're just going to hard code those by putting them as a default value here so going up to our state we can pass in an object here and this is where we can Define our default options so going off of this code again we will copy these options here that they recommend and we will bring that over and paste that inside of our options now what we need to do is when we select a drop down value which is going to be here on change we will make a new request and then update the data state which will cause the value down here to render so what we'll do is we'll say axios die get pass in some URL here which we'll go grab one in a second dot then this will have the response and then here we will set data like always I just like to check my sanity make sure things are wired up correctly by doing a console log I don't know why I'm commenting that okay and we will just say getting crypto prices so for the API we're going to use coin gecko again and there is one endpoint in here to get the historical data for a cryptocurrency and that is Market chart get historical Market data includes price market cap and 24 hour volume within a range of time stamp so let's try this one out what we will need to do is we will need to pass in the cryptocurrency ID such as Bitcoin compare this to some existing currency such as USD this one is going to take a from date Unix timestamp and a two date Unix timestamp the alternative one just this Market chart without the range is actually going to allow us to pass in just a number of days so that's what we will try Bitcoin USD and then for the days let's go ahead and put 30. now the interval you can pass that in as well so for example we could say daily to get one value per day hit execute take a look at the data that we get so it looks like there is a time stamp and then some price so we can use the time stamp to show where this should display on the line chart and then the value to show how high it should be so this will be the x-axis this will be the y-axis and then we'll just convert this timestamp to something that's not so ugly so let's copy this URL here and we'll bring that over to our application paste that right here and then let's go ahead and console.logresponse.data which I guess Works instead of just printing this random thing here so let's try that out we'll go over to our site we'll select some cryptocurrency and we get an array of 31 which includes one extra day you can reduce that if you want by getting rid of one or 31 is fine for me so we have a bunch of arrays and each array has two values so pretty much what we need to do is get all of these first values for the timestamps and then all of these second values for the actual data but now that we have this data we can start creating that data object that we need to pass in so let's take a look at their example to get that structure so I'm going to copy this object and we're only going to have one data set you could do multiple line charts if you want I'll just delete one no big deal we'll say set data and we're going to pass in that object you can see some issues so let's go ahead and fix these the labels are going to be the timestamps what shows up on the bottom and then the data is going to be the actual values and we're only going to need one of these lines so we'll get rid of one and now we just need to assign something to labels and just as a quick example let's do like one two three four and then for the actual data we will also try it out we'll say data and we'll create another array four seven ten and three and I'll add my comma there make sure everything looks good and let's just test this out to see if we can get a line chart to show up so I'll select a cryptocurrency and we do in fact get a line which follows that data so I got one two three four and then four seven ten and three so before we go in and get all this data I want to just resize this a bit to make it look a little bit uh more reasonable so what we can do is surround this in a div and then give the div a width so earlier on in the series we've used Tailwind for everything but I haven't actually installed that for this application so we're just going to do a basic style here with 600. there is also some support to pass in sizing as props to the line but I found this to work easier for me and it looks pretty good whenever you want to go through an array and grab one element from a bunch of the nested data that's where you might want to use map which we've used for looping through content the parameter is going to be assigned each individual item in that array for each iteration what we can do then is just grab the individual items in the array so what is that code going to look like we're going to jump in to where we have the labels and just say response.data dot map now before we say map this is a function on an array so we need to check the data because it's actually an object where we have the prices so instead of doing map directly we need to say prices dot map and then inside here we will pass a function and the parameter is going to be an individual price and the type of this is going to be a number array and then all we'll do for here is just say return price index and we want to grab the label which will be the time stamp so taking a look back at the data the timestamp is on the left here so index 0 and then the price is the next one so we will say price index 0 to grab the time stamp we're going to do something very similar for the data down here so we'll say response.data Dot prices.map and same exact structure we will have a price which is a an array of numbers and we will say return price index one so let's save and take a look at what we get we will select some cryptocurrency aha it seems to be working so we get the cryptocurrency price we actually I'm like what is going on well these prices are whack but I'd realize we hard-coded Bitcoin in the URL so sorry there's a bunch going on here so we need to do is we need to substitute this value so we will just say whatever the crypto price we are trying to select and I'll use backtick so I can easily substitute a value in here what crypto are we trying to select well it is C dot ID and this should allow us to change which cryptocurrencies being selected so let's track now we can go in here and choose cryptocurrency and those prices are a bit more reasonable so far not so bad but we might want to update the time stamp values to be more readable dates and you can do this various ways you could try converting it to a date object I'm going to use moment which is a package we can easily install and use to make nice formatted dates so to get moment we're going to say npm install moment once this is installed we can import it so let's go up to the top and we'll say import moment from moment now to use moment what we'll do is we'll go to where we are getting those date values so this here and instead of just returning the timestamp we can actually convert it here to convert it we will say return moment dot Unix and this is a method call where we will pass in the price and then dot format will allow us to specify what format we want this to look like so for example we could say month month Dash date date meaning a two-digit month such as 06 and a two digit date like one three all right so we'll save this and taking a look it's going to be closer to what we want yeah it's actually looking pretty good but you will probably be confused by these dates because look at these there's no consistency or pattern here it doesn't look like this is a daily chart and this has to do with the way JavaScript uses timestamps so this value that we are using for the price has the millisecond whereas the Unix timestamp expected for moment does not so what we'll need to do is just divide this number by a thousand and now the dates are a little bit more predictable let's go ahead and select a new cryptocurrency to refresh the chart so 917 916 9 15 and so forth if you display the year that would have showed up a little bit clearer so for example if we had year year and we did not have this division by by a thousand you would see dates that look like this which is definitely not right so definitely make sure you remember to do the division by a thousand and there you go that's all we're going to do in this episode in the next video we're going to talk about how we can change how much data to be displayed so we could switch it to seven days or even one day and cause a Refresh on that chart we also talk about the chart options and how we can change the title to show what cryptocurrency is being displayed in the chart so stay tuned for the next video it should be pretty cool and be sure to subscribe I'll see you in the next one peace [Music] what's up YouTube in this episode we're going to worry about creating a drop down that will allow us to select the range of data we want for our chart so this is a cryptocurrency price chart we can do 30 days seven days or a single day in the previous episode we built this where you can select a cryptocurrency from this drop down and it will change the chart so the very first thing we're going to do is we're going to create another drop down with the different range options we will allow then we will make a change to either of the drop downs refresh the chart so let's take a look at our code here we have where we're creating the chart and it's on change for this select so we'll just go to the bottom of the select here and we will create a new select this one is just going to have some hard-coded values so it'll be a lot easier to create so we'll just create an option and say something like 30 days and this is what it's going to look like so far so good now we can just add this other options in there so I'm going to go with 30 days seven days and one day now we have these options here and what we'll do is we will create a very similar function to this we're just going to change that Network call so if you take a look at what we currently have when we select a cryptocurrency we'll grab the most recent request this is the URL and you can see it has currency that to compare it to is the USD and days is 30 and the interval is daily so we can modify this API call depending on which item is selected so let's just iterate through this we will start by creating an on change here in the select and this will be a function this function call is going to have an axios.get and the URL we're going to get will be actually the same as this one here however we'll just need to change it a bit so this URL is from coing Gecko and you can see maybe the first problem here which we are using this variable here this refers to the selected element from the other drop down so how would you get what item is currently selected if we're not inside of this on change where we have the event well one way we could do this is to set some State such as current selected then down here you could just use that state instead of this C dot ID but then we would have to do the same thing up here because we would want to maintain the range that we are currently using so we couldn't just hard code interval daily in days 30 here we would need to update this with the current selected range option which we're defining down here you know maybe it's one day or seven days so we'd have to do the same thing where we assign this to State and then reference it in the other API call so basically we're going to flip this one's going to use an event for the ID and state for the range and then this one down here is going to use State for the ID and the event for the range so that can work that's how I actually designed it initially when I was just going through a run through of this code personally so the problem though is that it's a little bit more complicated switching between the state and the event so why don't we just keep everything consistent and use state for everything in this situation all you would need to do is update the state whenever you change one of those drop downs and then Define a function in one single location that's invoked for any of those changes you might think just to define a function and use that name down in those event handlers but what is the actual best proper way to invoke some code when there is a state change well that is actually use effect so we will create a use effect with a dependency array of those State variables if that's a bunch of words that don't really mean a lot let's just go ahead and try this what we'll do is we will say use effect and inside of here we will pass a function and then the dependency right here is going to be some State we Define for the selected crypto so the crypto that we can get the ID from and we'll just call this or the range for example which will be the days and we can just adjust the interval hard-coded so we will just have this for the days so let's go ahead and Define some State we already have a selected which we can use for the selected cryptocurrency the other thing we're going to need though is the range so we'll say range and set range and this will come from you state and we will give this a default value of 30. now it's going to be a string passed in the API if you want the actual data to be stored as an integer you can do some hacking around that but I'm not going to worry about that this is just going to be a string and now what we can do is we can make this eu's effect execute Whenever there is a change to the selected cryptocurrency or the range and inside of this function we can Define the API call now our existing on change is going to be thinned out a lot we are still going to want to set the selected here but the actual API call is going to be moved to that new use effect so I'm going to take all of this code here and just hope I can get the correct parentheses think right there so now this is what our new on change looks like and we can move this entire function call up here so paste that and we'll need to modify it a little bit so instead of C dot ID which came from the event we will substitute this with selected dot ID and we can do something very similar for the days here so instead of hard coding days there we will put range and then we'll just test this out see if it works but until then let's just go fix these on changes so it's going to be fairly similar for this one down here where we just set the state so we have our select we're not going to need to make an API call so we will just say set range and we'll get the value from the event so e dot Target dot value and because we want these to just be the 37 or 1 well we will want to give it a value here 30 and then 7. and then lastly we'll just do one Let's test this out so we'll select cryptocurrency change the state well tether was such a bad option let's go with another one change the date 30 days seven days and one day we might need to do some custom code for one day but you can see that changing this drop down does in fact refresh the chart so far so good a reminder that API does return eight if you put in the value seven so you can see there's actually eight data points here I'm really not too worried about that but if you want you can drop one from the array or just request six days instead of seven so for example if you put the value 6 here well now when we choose seven days we're actually getting seven values and you could do some similar for 30 days as well which I think returns 31 so you could change this value to 29. Let's test it out and feel free to count those if you wish I also wanted to try changing these to numbers instead of strings so 29 six and one and we will change the state up here and you can see it says argument of type string is not assignable to parameter of type set State action number so even though these are typed as numbers here when we get e.target.value it's given back as a string it's probably best just to do strings but you could also do parse and and pass in that value so either one of those works let's try just to make sure I'm not crazy so select crypto and then change the days now let's take a moment to talk about the one day and what I think I'm going to do is just change the API request to change the interval to hourly if we have selected a day so to do that we can go to the API call here and just do a ternary we will do that with a dollar sign curly braces making sure this is within back ticks and we'll say range being equal to one now make sure you get the type here you see if we put this in quotes we're going to get a typescript error so we'll just use the value 1. if this is true we will say interval is hourly otherwise we will say what we have out here already so let me just move these curly braces to the outside like that and then surround this in quotes so if range is one we want it to set interval hourly otherwise we'll say interval daily and let's make sure I don't accidentally have any spaces or anything in here so everything should be connected let's try this out we'll take a look at one day and it already appears to have improved so now we have hourly data and let's switch to seven days make sure it still looks normal so what we can also do is we can change the format you can see for a first couple of hours it's 9 18 and then it goes to 9 17. let's instead switch it to an hour format so what we can do is we can do the same exact thing but now for the format so if the range is one we can change that format so let's try that so we will replace this here with a ternary we're already in JavaScript so we can just put the variable we don't need curly braces and we'll say range being 1 we will change the format to our hour coin minute minute otherwise we'll keep it as it was with month month Dash day day save let's take a look now and you can see we get the times of the day the minute is pretty much the same so feel free to drop that if you want so just look like that but that might look strange too so I'm going to keep that on there and then let's check the seven days and you can see it looks the same as it did cool so we got the chart updating now we just need to worry about updating that title which will work in a very similar way you can see we have the default options defined up here but you know we don't just want to use chart J as a line chart for our text every single time so we can Define the defaults up here if we want but we can update it down here where we have set data we could also set the options so we could Define a new call here set options and pass in some new value so let's go ahead and copy this object that's defined up here all right here and I'm gonna I already got the curly braces so we'll just grab that and paste that down here paste the text we could just put something like well I don't know let's go with price over last plus range plus and then days there we go let's just see if this is working before I get too deep into this let's go back it says price over last six days that's not what I want because now it's basically off one because of the weird changing to the actual value we did so ah screw it I'm just going to change these values back that'll be the easiest fix boom and then if you want you can just remove one of the elements from the array so price over the last seven days similarly we can do a ternary to remove that parentheses s so let's find that we will just Define this as a ternary instead so if range is equal to one oh and we don't need curly braces either because I'm already inside of code then we will return day and let's go ahead and capitalize these values otherwise we will say days and I will put a period for both of these and then we will surround this in parentheses like so and then let's change to one day there we go you can add the crypto name in there as well so dollar sign curly braces and then just selected Dot name and now I should say Monero price over the last seven days I don't find this too helpful because we're only working with like a single cryptocurrency if you had multiple charted that'd be kind of cool but you can remove this by setting Legend to display false and we'll do that for the default settings as well display false and now when we choose an option such as Bitcoin you can see there's no more Legend here and if we change this it's still no more Legend one other problem I wanted to show is that on page refresh we are getting an error in the console and this is because we are making a network request with an undefined cryptocurrency as nothing is selected this use effect we defined is executing on initial page load so what we need to do is we just need to say if not selected and then say return so now in theory when we refresh we shouldn't get that Network request so far so good and we should still be able to select a cryptocurrency and everything works as expected this should also fix the scenario where we select the days first we're not getting anything if we didn't have this line let's just remove this for a moment what will happen is it will allow us to choose a day and it'll make the network request before we've chosen a cryptocurrency to display so definitely want to make sure we have that line in there so that's all I got in this video I was kind of interesting trying some different options with this chart what will we do in the next video I don't know I guess we'll just have to come and find out so hopefully whatever we're doing is exciting we might build upon this or try something new thank you for watching stay tuned be sure to subscribe peace out what's going on everyone in this episode we're going to start building a small cryptocurrency portfolio calculator basically you can add a bunch of cryptocurrencies type in the amount that you have of each of them and it will basically multiply the amount by the price add all those up and give you your total portfolio value we're going to use some of the functionality we created in the previous episode so I'll show you how to get this code exactly as is so this drop down allowing you to select a cryptocurrency we're not going to have the price chart in there but the ability to get the cryptocurrency and the price to add it to our list we're going to use a similar Behavior so over in our code I have a repo and I'm going to commit this and it's going to be called finish chart and I'll say get push and here is the repo you can find all these commits so just go to the commit history and you can grab the code for any specific commit so the first thing I want to do is work on this coin selection Behavior so we have this drop down and when we select a coin it will display the price well I want the next ability to select a different cryptocurrency and instead of replacing the previous actually add it to a list so for this instead of having a single selected cryptocurrency if you take a look at our state we have this selected this is a single crypto this is now going to be an array and that's going to create a bunch of problems in our code but that's okay because we're actually going to be removing a lot I hate to remove everything around our charts because we might end up adding some charts in so for now I might just comment some stuff out I hope that's not too annoying but let's go ahead and comment out the data and the options for the charts so we're not going to need those so we will comment out to here and we're going to need this use effect which gets that list of cryptocurrencies to choose from but we are not going to need this use effect which is dependent on the selected or range being changed so this is purely related to the Chart so we're going to comment this out that way we can just clearly see what is going on this one probably would have been fine to leave uncommented because it's not going to be invoked but you know just for clarity's sake we're not using this code so we might as well comment it out now for set selected we're no longer going to be pushing in a single crypto so we're going to have a list and we're going to take all of what is already selected and then add in the next crypto and it's not an array type so let's go up to where we defined the selected State and we will default to this to an empty array and we will remove the option for it to be null we can define a specific type for this cryptocurrency so we can say as crypto that'll remove that error down below and now let's take a look at the HTML we can remove the second select now for displaying the actual crypto summary like the price this is now an array instead of a single cryptocurrency so we're not going to just be able to say crypto and then pass in an array instead we should map through it and then for the actual chart which we're not using anymore we can just comment this out so comment there and then end the comment right here all right we're so close now we just have to worry about this one line to get rid of this error it says type crypto array is missing the following properties from type crypto so basically this is expecting if you go to the definition something of type crypto and the type for that is to find here where we have these properties that we want to look at well an array doesn't have these properties on it so what we need to do is we basically need to Loop through and do this for each one of the cryptocurrencies in our array so let's just push that down for a moment and we will say selected dot map and pass in a function this is going to have a single selected item s selected I don't really like that name choice because there's not a singular and plural which I tend to like for example crypto and cryptos but it'll it'll be fine now we can do is return a crypto summary passing in the crypto as s and then we will close that and make sure everything is matching looks good now let's just comment this line out you can use multi-line comments like so save that and let's take a look at our site so we choose an option we will choose ethereum it has a price there let's choose another one and it adds it to the list so far so good we've done a lot of refactoring so much so it might have been easier just to start from the beginning but yeah it's whatever can't go back now so let's just go in a little bit deeper and try to build the ability to type in how many we have of any cryptocurrency we'll worry about the aggregation later on let's just worry about now a single cryptocurrency where do we want this input well for every single one of these cryptocurrencies we'll want to be able to put the amount that we have so that would make sense to include inside of the crypto component since each one's going to have it so this crypto summary that we're rendering for each cryptocurrency we've selected we could put the input inside of that so now instead of just returning the name and the price we could return an input as well so let's try that let's go ahead and change this code a little bit just to allow for some extra typing so we're going to return all this and that'll allow us to bring this down to the next line and instead of a paragraph let's return a fragment and inside of this fragment one of the things we're going to have is a paragraph now but this will allow us to add some additional stuff in here so not only do we want to paragraph but we also want an input and this is going to have a default value of let's say 1000. taking a look at that it's going to look something like this let's go ahead and actually put these on the same line so let's just change this paragraph to a span and that should bring them together after each one we could put a break or even better we could just replace this fragment with a div and that's going to space things out so we'll open the div and end the div and there we go kind of looks like garbage but remember we're not styling in this video we're really just worrying about functionality but that is extremely hard to look at so let's just add a little bit of styling and we'll just say margin and let's go with 10. I should space that out a little bit better so it doesn't look like complete trash now it just looks like sort of trash so we'll create some local state for the amount that we type in here we will have that defined right here so const amount set amount and this is going to be you state and this is going to need imported so we will say import use state from react and now that we have state for this we can have an on change for the input so let's define that here on change and this is going to be a function call with an event and we will say set amount passing in e.target.value and the inputs are of type string so you can set this to type string and again this brings up the idea that you could parse the input value to a number and use that for state if you wanted the internal state to be of type number but this is fine for me and now we can replace default value with value and it's going to be assigned the amount so we'll save and this should allow us to change its value here and that will update the state for each one of these I do want to have a use effect for now that will allow us to see the state so let's go to find that here use effect and we will import that from react as well use effect here and this is going to take a function and no dependency array because I just want this to update for any state change console.log let's include the crypto dot name and the amount all right let's try it out so we'll go into ethereum we'll say five probably amplify the console open so ethereum is five and then let's go ahead and change binance to 50. now you can see an interesting thing here which is we created this use effect with no dependency array however when I change binance the use effect for ethereum is not displaying its data down here so this use effect with no dependency array which should execute on any state change is only worried about the state in this component so since these two rendered components are siblings the use effects do not see each other now what I want to do is calculate how much value we have of any cryptocurrency by multiplying your quantity by the price of that cryptocurrency this functionality is easy all you have to do is go in here and say crypto dot price and multiply that by your amount and you can just say parse and and pass in amount and it says argument of type string or undefined is not assignable to parameter of type string so you can just give this a default value say the string zero one other slight change you can make is actually set the input type to number which can help do some front-end validation for the input so let's try this out we'll choose a cryptocurrency and then we can type in some number such as 50. we have 50 it would be worth this amount so we can just take this value and then display it on the page and also having this as a number type you can't type in words but you can type in the number e because there's some numeric meaning behind e however it does help prevent garbage data from being typed in here so it's definitely pretty helpful so let's go ahead and try changing the display to include our value so not only will we have an input here but we will also have another paragraph and this is just going to contain crypto.current price and then we'll just multiply this by our amount and I thought of something instead of Parson we'll probably want to use parse float as we could have fractional amounts so parse flow amount and we'll do that same thing for right here parse float all right so now we should get that value right here and you can say dot two fixed to improve the formatting so dot two fixed pass in two and we don't want to actually invoke that on the parse float value but the final multiplication result so we'll surround this in parentheses and then say dot two fixed pass in two and we can also prefix it with a dollar sign so now we get something like this one more fix you can add commas with a quick function call instead of two fixed we will use dot to Locale string and this will take two arguments the first you can pass in your Locale or location and you can research that if you want but we're just going to pass an undefined to skip that argument and instead just focus on the second argument which is settings or options which will be passed in as an object and inside of here there's two things I care about which is the minimum fraction digits which is going to be 2 and then the maximum fraction digits which is also going to be 2. saving this let's take a look at our site now and we should have two digits after the decimal and we have commas and our number now so let's just go through some different examples so even if it's zero it's dot zero zero and we always have those two decimal spots and there's lots of different things you can customize it so for example in the case where it's zero you could look up how to remove that but I actually prefer it to always have the decimal there that's all I got in this episode in the next video we're going to figure out how we can add up all of those values to get a total portfolio value and then from there maybe we can do something cool such as creating a pie chart showing our different cryptocurrency amounts looking forward to the next episode be sure to check it out foreign [Music] we're going to learn how we can aggregate a bunch of data together to do a total crypto portfolio value this is going to be pretty interesting because we're going to learn how to deal with nested objects and aggregating data across those objects so we're going to get some experience with map and reduce right now here's how we have it we can add a cryptocurrency in here and put some number so 500 ethereum will be worth that much and then if we add another one in here if we had let's say 100 Bitcoin it'd be worth this much what I want to do is take these values and add them up at the bottom it sounds pretty simple like oh this plus that but these are components so what we need to do is we need to figure out how to move their state to their parent so that way the values are managed by this entire page instead of just a single cryptocurrency so let's first take a look at this state here where this is stored and how we can move this value to the parent and how to deal with not a number this is a pretty easy fix all we have to do is create a condition to say hey if this is not a number don't display this instead display something like zero so let's jump over on our code and I'm aware we have some stale code that's commented out and we'll try to clean this up as we go but if you've been following along don't worry about that and if you're just jumping in also don't worry about that so let's just go into the crypto summary and this is the component that describes each one of these sections so if we select one of these this is the crypto summary component and we can render it multiple times for different cryptocurrencies there is a state here that is defined as the amount and this is what is being typed in right here now I set this to type string and I've had this Massive Internal debate the question is should you parse the data immediately and store it as a number or should you store it as a string and then parse it whenever you want to use it as a number hopefully that makes sense but right now the way we're doing it is we are storing it right away immediately as a string and then anytime we want to do some math operation on it we will parse it to a number and I thought that was the way I wanted to do it in the previous episode but since then I've changed my mind because I'm indecisive here so we're going to do is we're actually going to store the value as a number because throughout this video we're we're going to be doing a lot of more operations and I don't want to have to deal with parsing and all that stuff so let's go to this state and we will change this type to a number and we will default it to zero not as a string this is going to break everything so let's get rid of parsed flow anywhere we see it and here's well now this is where we will do the parts this is the input so e.target.values coming in as a string and we will say parse float and pass it in like that now some people will also use number so passing it to the number Constructor which should also work but I'm just going to go with parse float here and then same here we should already have it stored as a float so we no longer need to do parse there and then last thing I accidentally just screwed up the parentheses there so there we go everything should be working let's save and let's just check to make sure where things are working we expect we should be able to type in values in here and get some value down here so everything should be the same but now we have less typing when we want to deal with this amount of value now this amount is tied to this single component so how do we actually push that up to the parent well anytime you want to do that you're going to actually want to pass down a function from the parent which in our cases app and then take that in as a prop inside of this component this will allow us to invoke that function whenever we need to make a change so where are we going to make that change it's going to be right here so this would be set the parents State now I'm actually still going to keep this set amounts just because it's pretty simple to work with and our parent state is going to be an array of nested objects which is super complicated so we'll just keep the amount and the set amount here in this component and use them so basically what we need to do now is we need to set the parent state by calling a function passed in as a prop okay so what is that function going to be well we will Define that right here whatever function we are expecting we need to set it as one of these properties so let's just say it's called update owned so this is going to change the amount that you own and the way you say this is a function is by defining the structure of it like so where the parentheses contain the parameters and after the arrow has the return now I know ahead of time this is going to be a void function because it's just going to update the state it's not going to return a value and then we can pass data to it so for passing data to the parent we'll probably need to know which cryptocurrency we're talking about and then how many we currently own so I will have two parameters here the first being the cryptocurrency that we're working with and that's of type crypto and then the second thing being the amount and this is going to be of type number so far so good and then what we'll do is we will just retrieve this value with destructuring so we'll say update owned and this can be invoked down here so we'll say update owned and pass in the crypto that we are working with and the amount that we're going to change in the state which is going to come from E dot Target dot value and we will also need to parse it here so we will say parse float and pass the need.targetable value so we've talked a lot about how this is going to be used in the child component to summarize our change we just took in an additional function and passed those values back to the parent now inside of the parent we can create a function to update the state so where are we going to Define this I'm just going to Define it right before our return so I'll have it right here and we'll say function update owned and then we will Define this to match that structure so we're going to have the crypto parameter and this is of type crypto and then we will also have the amount which is going to be of type number so this signature here should match exactly this signature defined here now we don't actually have the return type defined here you can if you wish just by saying void but this is optional and if you decide to not include this the return will be inferred by whatever's coded inside of these curly braces so right now if we kept the void there and we said something like return five it's going to complain and say type number is not assignable to type void so if you know it's going to be void you can leave that in there and you'll be sure not to screw it up now that we have this function defined we can pass it to the child component so down where we are mapping through the selected cryptocurrencies and rendering the crypto summary we can include another property which is update owned and pass in that function update owned and we're not going to have parentheses here we don't want to invoke it we're just passing that function to be invoked later now now we're not getting any problems because these props that are passed in match the crypto summary app props defined right here before we included the update owned it was giving us an error now I did want to share one thing and that is let's say this update owned was optional this is totally theoretical here it's not actually our case but let's say we wanted to be able to not pass that in if we wanted right now it's complaining but whenever you have an optional property you can go into the defined types for those props and you can put a question mark before that colon and it'll say hey this is optional you will need to do some conditional rendering down here so basically saying if update owned exists then we can invoke it so you might need to turn this into a ternary by saying update owned question mark then invoke it otherwise null so that is how you would modify this code if you had an optional property now it doesn't really make sense in our case to have the optional property but I just wanted to show that to you guys for completeness sake so let's go ahead and put that back to how it was so we are guaranteed to have an update owned or it's not going to compile so we can enforce that without the question mark there and now we will just pass it like we originally were so we are back to where we were now the last thing I want to do is just add a console log to our function to make sure everything is wired up and then we will build upon that so let's just console log update owned and we will console log the crypto that's passed in and the amount that is passed in so this can make sure we're getting the correct values that we will then use to update the overall selected cryptocurrencies state so let's take a look at the site and we will open up the console and let's just get a clean start we'll clear that out refresh the page let's choose an option such as ethereum and say we have 10 ethereum here is our console log from update owned a little misspelling there no problem and this is the object that we have and then the amount of ethereum we own is 10. great job if you were able to get that wired up consider this a checkpoint now we have to figure out how we can keep track of that owned amount and aggregate all of the owned amounts across all the different cryptocurrencies to get a total portfolio value so we need to add it to State somehow now there's plenty of ways to do this I'm sure you could create State and this will keep track of which cryptocurrencies and their amount and then you can go through that to add everything up or an alternative option would actually be to add a property to that cryptocurrency object which keeps track of how much is owned that's what I'm going to go with but if you want to go a different route or you think something might be easier definitely give it a shot and maybe drop your suggestions or how you did it in the comments section below but pretty much what I want to do is add a property to this cryptocurrency called owned and that's going to be a number with a value 10. so what will that make our state look like well you could see it if you just print out the entire selected state so console.log selected and let's run this again real quick We'll add a cryptocurrency and we'll just set an amount 50. you can see this is our array and we'll have each individual object in here where the property owned can be added up across all of them to be displayed on the page so there will be some nesting and it's kind of complicated but I'd like to keep everything in the same spot so let's define that value on the type so if you head over to types here's where we defined our crypto type and we can add a new property that we care about here which is owned and this is going to be of type number now if you did decide of going the route of storing it as a string you will want to make this a string variable but it just makes sense to be a number for me so that's what I went with now the way I'm going to do this is I'm going to take this array and get a temporary copy grab the object I'm looking for by its ID that matches the ID of whatever value we're selecting and we'll update it to contain the amount owned and then assign back the temporary array to replace the existing state so sounds complicated as crap probably because it is but let's just go ahead and try to do it so what we'll do is inside of this function we will first just clear this up I'm not going to keep that I'm going to create a temporary variable which is going to be a copy of the existing selected array when we then assign this new array to State it'll be seen as a new object and will re-render the page now inside of this array we will try to find the specific object we're looking for so you'll say temp dot find this is going to take a function and this function will have a parameter which is going to be each of the cryptocurrencies inside of this array so I'll just call that c and what we'll do is instead of using curly braces here we'll just do a comparison directly and say C dot ID is equal to crypto.id where this crypto variable is the parameter that was passed in right here so basically if the argument crypto that was passed into this parameter here ID is equal to an ID inside of the state array we're going to return the state array object C and that can be assigned to a variable as well so we'll say let temp object the temp.find and now we can modify this temp object by saying temp object Dot owned and assigning it a value of the actual amount that we now own which is also passed in as an argument now we do get an error at the left hand side of an assignment expression may not be an optional property access so you get rid of that for example but then you get another error object is possibly undefined so the solution to this is to actually do an if statement if temp object exists then we will assign a value to it so it'll look like this that's going to change the object in the array which we can then assign back to the original state we can say set selected passing in our new and improved updated array and I want to track this progress so what we'll do is we will create a use effect that is dependent on the state so it'll look like this with a dependency array of selected it's the only thing we care about for this and inside of here let's just console log selected and comma selected so we can see the entire selected state so let's give it a try we will choose a cryptocurrency such as Bitcoin put in a number such as 10 and you can see our selected State here we'll have one object inside it and inside the object we now have this owned value of 10. so far so good let's try adding another cryptocurrency and we'll have let's say 500 of these and taking a look at this now we have our new updated State selected and the second one will also have the owned 500 and the original one has owned 10. so far so good now we just have to go down to the bottom of our HTML page aggregate that data and display a total value so inside of our code we will scroll down to the bottom of our return right before this fragment and that is where we are going to display this and what we'll do is we will say if selected exists we will do selected dot map passing in a function otherwise we will return null here and let's test this out so each one of these we'll call S and we will return let's just say a paragraph for each of these and let's put in here s dot current price multiplied by s dot owned and that should give us the value for each of the cryptocurrencies we own just to show that we can now include s dot owned in our math so let's just go through an example from the beginning so we'll say Bitcoin we have 10 of these and it includes our value down here as well and we have ethereum let's say we have 10 of these and you can see we're now displaying two of these so how can we go through and add up all of these values in this map well it's an additional function called reduce so to do this instead of returning a paragraph we're just going to return the value and we're not going to need the curly braces anymore since we're not inside of HTML after the map function right here we can say dot reduce and this is going to take a function as well and you can also include a second argument which will be the starting value so we'll say zero so this is going to have two parameters it'll have a previous value and a current value in each iteration it's going to add up some value and return it in the next iteration that'll be signed to previous so all we have to do is say return previous plus current save let's take a look and it should give us a total so a hundred and ninety thousand nine hundred plus thirteen thousand is roughly two hundred and four thousand so let's look over that one more time we have the current price multiplied by how many you own this is going to then be passed into reduce which will iterate through all of the different cryptocurrencies adding them up and returning that value if you want to see this in action what you could do is you could console.log previous comma current and I know we got a bunch of console logs going on here so let's just say prev current inside a quote so we can really easily find that in the console and let's restart here and clear out the console so we'll choose a cryptocurrency such as Bitcoin say we have 10 of those and then we'll add another cryptocurrency ethereum and before I change this value let's just clear the console one more time because it's going to show the whole process in the display say we have 10 of those so the first iteration previous has a value 0 and current has 191 000 which is our Bitcoin value the next iteration that value moves to previous 191 000 and the next value is our ethereum value 13 451. if we had a third one in here it would combine these values and that would be the next previous value so if you want to see that we could add a third one in here such as tether clear this out and we will say we have 10 of those as well that third iteration is the combination of Bitcoin and ethereum and then tether last thing I want to talk about in this video is dealing with not a number which does show up quite frequently when you're working with this application so for example if I remove these well this is not a number and that's not a number which is just really bad so what we can do is we can change the way first this component is displaying the value of the tether and then we will worry about everything combined so let's go over to the crypto summary and find where that's being displayed we have it displayed down here we can just do a quick condition so here we can surround everything in a ternary so I'll put the curly braces and say if it's a not a number which you can do that with a function call if it's not a number passing in the amount then we will return just a string saying zero otherwise we will return a string starting with the dollar sign followed by the rest of this which we can remove that set of curly braces now actually and then include a plus sign here so that should fix the first one give that a quick save and now if we don't put in a value here we get zero it still doesn't fix this problem down here where the aggregation is not a number and this has to do with the internal value the amount is still not a number and we are trying to aggregate that with other numbers so we're getting not a number and that's going to be defined inside of app where we are doing this map we are multiplying the amount owned by the current price which if the amount owned is not a number this multiplication is going to give us not a number which we can then not Aggregate and add up in the reduce so what we can do is actually just create a little condition and say if it's not a number ignore it or just return zero so we will go in here and say if is not a number s dot and we will then return zero otherwise we will return the multiplication of owned and current price let's check it out now and we leave this empty and we still get a total value now all we need to do is just format this value and we can do it the same way we formatted each one of these so let's go ahead and try that out once we are finally done with all these function calls we can say dot to Locale string passing in undefined for the Locale or is it Locale I'm not too sure and then for this we can pass in the minimum fraction digits being 2 and the maximum fraction digits being 2 as well so that should format it a little bit and we got the commas now I just need to prefix it with a dollar sign so we will just have a dollar sign right here and add that value to it there we go it's beautiful now you can just add a pretty message your portfolio is worth and display that there that's all I got in this episode we got the portfolio value now what we could do if we wanted is we could create a pie chart splitting that up based on the total values for each one of those cryptocurrencies I think that'd be a cool addition to this app maybe we'll do that in the next episode see you then be sure to subscribe and peace out what's going on everyone in this episode we're going to continue building our suite app which is a crypto portfolio calculator and this will allow you to choose multiple cryptocurrencies from a drop down list so let's say we had Bitcoin and ethereum we can then put how much we own of each of these so let's say we own 50 Bitcoin and let's go with 72 ethereum this is what each one of those are worth and then it'll sum it up down at the bottom the goal of this video is to go through and clean some of this up to give a better user experience and then display a pie chart showing those different cryptocurrencies so we're going to use react chart js2 and it's going to look something like this however instead of just colors and a number it'll have that cryptocurrency and the value so that way we can see very easily which cryptocurrency is the biggest or the smallest percentage in our portfolio so the first thing that was challenging me with this is that when you add a new cryptocurrency it defaults to zero so so that's fine and all actually you know that makes sense but when you click it it puts the cursor there so then you actually have to delete and then type in a value which isn't a very nice way of working with this so I wish this just defaulted to empty and I was struggling with the best way to do this so if there's some secret definitely drop it in a comment in the comment section below but the answer for me was just to switch the default number from 0 to not a number which is actually kind of funny but this is of type number so it works so everything works out with the types and we don't get any problems and now when we add a new cryptocurrency let's just do a refresh we will go in here select a cryptocurrency it defaults to being empty and then we can go in and type a value as a much better experience you know I was thinking of maybe working with default value but we want this to be tied to this amount and wasn't really sure how to show the amount let's say this defaulted to undefined year well then we get errors and we have to go through and fix up all of our code and the reality is when we actually delete the value here that is what is shown up as the value so if I delete this you can see that the quantity of how many ethereum I own is n a n or not a number now let's go ahead and take a look at this pie chart what we're going to need for this is data this is going to be passed in when we create the pie chart we're not going to have the various settings we had in previous videos which we defined in this options here so what we'll do is we will just remove this comment and then get rid of this entire options here so we'll keep data then we'll just change some of our Imports so going off of here we will need to import Pi instead of line if you are following the earlier videos and we will need to register this Arc element which will need imported as well and the register is going to be limited to just Arc element tooltip and Legend so we can clean this up a bit so let's first import Arc element and add that to our register right here and then we can get rid of these extra ones we're not going to need since we're not using the line chart now when it comes to the type well we're not going to have chart data of type line and so we're going to have chart data of type pi and our import is going to be import PI from react chart.js now let's go down to where we were creating the line component we have that section commented out and just so I don't forget I'm going to change this to Pi and we're not going to need the options passed in either perfect let's uncomment this section and just see how it goes pretty much if you're jumping in you'll just need to check to see if data has a value which we can assign data of value when we change the different cryptocurrencies that we own if data does have a value then we're going to render this pie chart so going off of that now let's see what happens when we select a cryptocurrency and put in some value nothing is actually happening and that's because we're not actually assigning anything to data when we change our cryptocurrency quantities so we'll just need to make sure we add that in now the easiest way to do that is to create a use effect that depends on the selected state so pretty much any time our selected cryptocurrencies or how many we own changes we will have that use effect execute so let's scroll up to the top and actually already have a very simple use effect to find that's just printing out selected we had something pretty similar where we were doing this in an earlier video setting data inside of a use effect so you can use this code for instance operation but it's pretty long so what we're going to do is just start from scratch and then afterwards we can delete that comment but as this is now it's going to console log selected in all caps so if we take a look and we change our portfolio you can see selected is printed right here so all we will need to do is invoke set data and it'll look something like this here you can also use the example from the pie chart as well for what data should look like so let's go ahead and copy this object that they are assigning to data and that's what we're going to pass into set data so I will take that or you can just type it out if you wish and let's head back over and inside of this use effect we'll say set data and pass in that object we're not getting any problems so let's just make sure that this shows up heading over to our site you can see that we get the pie chart we only want this pie chart to show up when we have some cryptocurrencies in our portfolio So to avoid setting data before we actually have anything inside of selected we can just check at the beginning here if selected dot length is 0 we can just return and now it's not going to show up on initial page load until we actually select a cryptocurrency now all we need to do is change how we are defining data so instead of hard coding the data and the labels we will get those from the selected array so taking a quick peek at what that'll look like if we add a few elements in here and give them an amount we can take a look at the selected array for the labels we will want to go through all the objects in this array and grab the name and then for the actual values we will want to grab the owned multiplied by the current price we can do this fairly easily with map so where we have labels we will remove this array and instead say selected.map and pass in a function here where the parameter each iteration will contain one of the selected elements and we can just return actually getting rid of the curly braces we can return s dot name without the curly braces it's an implicit return but it'll only work with a single line so if you need to do something more complex you'll add those curly braces back in and then for the data we're going to do the same exact thing except just change what data we want so selected dot map passing in and arrow and we will just say s dot and make sure we Define that S as a parameter there s dot owned multiplied by s dot current price saving this let's take a look now and it actually appears to be working so you can see our ethereum value 67 000 versus B and B is 8 000 so the ratio is much bigger to ethereum and you can visually see that very quickly with this pie chart so I'm pretty happy with this let's go ahead and add a cryptocurrency and see what happens let's go ahead and add polygon currently we have zero polygons so it doesn't even show up if we change our quantity to say four well that's only three dollars so it's a really tiny sliver in there so let's go ahead and say something like four thousand or forty thousand and you can see it starts to take up a bigger portion of the pie you can remove any of these if you wish and it'll remove that section and then just split it across the sum of these two values now I wanted to experiment I'm actually not sure what will happen if we add a bunch of these because we have our colors defined here so I'm not sure if it'll cycle through these or what let's just add a bunch we'll say we have you know we gotta add a ton of that because it's basically worthless um what else looks fun amp in here all right let's add a couple more Cava hey that's the name of my puppy should not really a puppy anymore but she deserves the world so we'll add a bunch of her and let's add one more here and let's make sure we have BNB enabled there we will add synthetics and you can see here now it is repeating a color so ethereum and synthetics is sharing a color so I actually haven't done much research on the colors so maybe there's a way to generate colors if we got rid of these all together I think it'll just use the same color every time but I'm not entirely sure so let's try this say Bitcoin and ethereum and give them some values and ah it's just gray definitely not what we want so you'll probably want to look how you can generate colors or just for example use random numbers for these different values to get different colors overall I'm pretty satisfied with the way our chart looks let me know down below what you think about it I think we could just clean up some general formatting to make this page prettier you know for example adding in the commas to these numbers here and actually saying what this means so maybe like total value owned and then here you could say complete portfolio value that's all I got in this episode hopefully it's been fun I enjoyed this little project it's pretty cool I like doing things with cryptocurrency and numbers so showing charts and stuff is pretty fun I'd say so however I am definitely eager to be doing something new because this is boring so let's go ahead and move on to the next topic don't forget to subscribe don't forget to check out the next episode I will see you there welcome everybody we're going to be doing something new in this video I am so excited I decided to wear white today which it's kind of blinding don't really like it so sorry if you can't even see because I don't know how you're even gonna click the Subscribe button if I'm blinding hair I swear I've been happily married for 27 years since birth this episode we're going to be taking a look at graphql the bear Basics getting it in your project and making requests to a graphql endpoint now what in the world is graphql well it's an alternative to a rest API so with the rest API you will make individual requests with different methods and get the appropriate data back with graphql you have a single endpoint and you can customize what you want on the front end taking a peek at the graphql website it says a query language for your API so if you're familiar with say SQL for databases well graphql is kind of like that where you can ask for what you want but you're going to do it from the client instead of structuring those query languages in the back end to the database if you have relationships and your data graphql can work with those very easily because it'll basically create those relationships in a graph like structure and you can grab the initial data and then grab nested data which would be connected to the original data so not only would you be able to grab the cost customers in a single request you could also grab all the customers orders in a single request and get that in a single structure back you can also customize exactly what attributes you want returned so let's say it's giving back the customer's address you don't need that for any reason you can just delete that specific field from the query that you're sending to the server the end result of this is that you're going to have one API endpoint which is typically slash graphql and then you just modify the request that you're sending to that endpoint to get different data now you can find graphql in a lot of different locations front end and back end so when you go to learn more about it you'll find there are a bunch of different languages supported and even within JavaScript there's a bunch of different clients that support graphql notice that these are split in two sections so we have client code and then we have all the way at the top here server code so this is a connection where you have to set up graphql in a server environment if you are managing your own API and you will have graphql on the client to work with that backend starting out we're just going to worry about the front end and consume an already existing API that's out there so what we're going to do is just scroll down to the client section and figure out which one of these we should use now we're actually going to just use the Apollo client which I believe is one of the most popular another really popular one is relay and there's some other ones on here Urkel I believe it's pronounced and a couple of others so yeah it can be pretty overwhelming the number of options but the important thing to know is that it's all built on the graphql query language so if you understand that language then you just write the same style of queries regardless of what client software you're using so we'll get started with the Apollo client and we are going to use an existing graphql endpoint out there which you can find at api.spacex.land graphql this is going to bring up a visual tool called graphical and all of the different queries we might want to execute can be done from this single URL so we can hit play with the default example here and it will display all of the data that we requested notice that we have a lot of nested data so for example we have the mission name which is just a single value but then we have links and links is actually an object with multiple properties coming up soon I'll show you how you can do this for your own backend but for now we're just going to use this SpaceX example because it's pretty comprehensive and gives you a lot of good practice this will allows to focus on the front end before we have to worry about the back end the query is completely modifiable so what we could do for example is we could remove this article link if we're not interested in it and now it's no longer going to contain that in the response you can also see the Explorer over here which will have all the different attributes we can retrieve as well as how things are connected so as an example we could select Rockets that's going to to add it to the query and then we could select a few of these different attributes that we might be interested in make a request see if anything new is returned scrolling through here you can see somewhere in here maybe Rockets so here is an example of that response so you have the boosters company cost per launch and the country which is exactly what we requested over here this gives us back a single Json response which is very friendly for the front end we don't have to worry about making 20 different API requests and managing that data on the front end we just make one and get anything we need so let's get started creating a react application to consume this graphql endpoint we will jump over to the terminal and change directory to wherever you want to put this code and we will say npx create react app and we'll just give this a name such as graphql and we'll go with the template of typescript which we're going to continue to use hit enter this is going to create a new react app in this graphql directory and we'll say code graphql from here we can open a new terminal which I will prefer to use over the one we just tied open and from here we can now go into our source code and clean up some of the stuff we're not going to be using as we've done in previous videos so we'll keep this one but we're not going to need the logo the test file the web vitals or the setup tests and then going into each one of these index.tsx we're not going to need that right here and we're not going to need this section down here next up we'll go into app.tsx we're not going to need the logo so we will remove this line and this line and then just clear out this component to just have the div next up we will just remove any of the CSS definitions just so we have a completely fresh application and also index.css as well that should be everything and now what we can do is we can install any packages we need so I'm going to zoom in because it's pretty tiny so we will go ahead and say npm install and we're just going to go off of the docs here so npm install Apollo client graphql so we need graphql as well as Apollo which is the client that we're using and we're going to write some code in index.tsx which is going to surround our entire app so first we're going to do some imports so we'll say import from at Apollo client and the Imports we're going to need are Apollo client in memory cache Apollo provider and gql so let's type this out real quick so Apollo client in memory cache Apollo provider and gql these are what we're going to need to set up everything inside of index.tsx now we have to create an instance of a client and we do that using this Apollo client here so we'll say let client be assigned new Apollo client this will take one argument which is going to be an object and inside of this object we're going to need a cache and you can see some tips down here and a URI so we'll start with the URI so we'll say URI and set this equal to some value and then we will say cash and set this equal to some value so for the cache it's actually going to be a new in-memory cache which we imported and then the URI is going to come from the endpoint we've been using earlier which is api.spacex.land graphql so we will paste that here and save now the docs are going to show us how to do this in JavaScript and then how to use the react equivalent which is to use a provider and then inside of whatever component using a hook use Query so let's start by just creating a simple query inside of index.js to confirm that we can get a response from the server so let's go back to our code and after we have defined client we'll say client dot query and this is going to have a DOT then which we'll just console log the result so we'll have a parameter result and we'll console DOT log result now the actual query takes one argument which is going to be an object this is going to require a query property so let's go ahead and expand this out and start typing query and this part's kind of interesting we're going to create a string and prefix it with this gql graphql like this so gql backtick and then our entire query is going to go inside of these fact ticks so going off our graphical example we can copy this however I'm not going to want all of this so let's just actually copy these first few things such as this here and I guess I'll grab some nested data too so we can see what that's like so we'll grab these here so I'll copy that and paste it here and now I will just copy these closing curly braces which are defined at the bottom of this query so that we can close off our entire query so I'll paste those there so now we have an opening curly brace paired with this one this one is paired with this one and this one is paired with this one so everything seems closed we'll save and we will start our server npm start taking a look at the browser we should see the data response here and you can see inside of the data property we have launches past and a bunch of objects inside of that array so congratulations you've made your first graphql request from a react client however we're not really doing this the react way which is to use the use Query hook so let's figure out how to do that now and put it inside of our app component or another custom component we could create we will use this Apollo provider to give access to the client variable throughout our entire application by defining it right here around app so we did do a video on contexts in this series so if you need a refresher you might want to check that video out but what we will do is we will define an Apollo provider and set the client value to the client object we defined earlier then we will take the closing tag and move that to after app now we can access this client inside of app and anything defined inside of app as well this is basically going to be accessible everywhere so let's go ahead and jump into app and we'll just Define some imports here so we'll import use Query and gql from at sign Apollo client and what we can do now is move our query from index.tsx into app.tsx so we're only going to need everything from the gql and then we can cut that and get rid of everything else including this then down here so a lot cleaner on this end and we will just assign this to something over inside of app.tsx so const get data as an example and then we will paste that value here and end it with a semicolon and now we can use this custom hook down here inside of app so we'll say const and this is going to have three values we care about loading error and data and we will say use Query passing in our query which we called get data to confirm this is all wired up we're going to create a use effect real quick and inside of here we can just console log all three of these values we can probably just leave the dependency right empty so any state changes will trigger this and we'll just import that from react so import use effect from react now taking a look at our site let's clear this off and do a quick refresh you can see these values false undefined and then the actual data which is the array so far so good this is making me happy now what you can do is you can just display this down in the return so it'll say if data exists we will say data Dot and taking a quick look at our data once more it is launches past so data dot launches past dot map otherwise we'll return null and inside of this map we will Define a quick callback function which will just return let's say a paragraph with and the parameter we'll just call it launch and I'm kind of ignoring typescript for a moment I know not really getting the True Value but whatever return paragraph and inside of here we will say launch Dot and taking a quick peek at the different properties we can just do Mission name so Mission underscore name giving that a quick save taking a look at our site and there we go we get the first 10 Mission names from our graphql query adding some typescript stuff in we'll just go ahead and copy one of these object examples and bring that over into our code and create a type up here I'm going to say export type launch and we'll paste this structure and then we will just modify it to have the types instead of actual values so this is going to be a string the date uh I think I'll just go with a string for now and then launch site is going to be an object with a property that is of type string saving this and we should now have that typing so we can say this is of type launch and Mission name is a valid value but we can also include other stuff such as launch dot date local saving now and you can take a look at the site and you get those times yeah not the prettiest thing in the world but just going in and throwing in that type script type so that we can know what to expect for the different properties down here that was a lot of information in one video we're going to be continuing graphql stuff for the next couple of episodes so I'm pretty excited about that hopefully you enjoyed this video and if this is your first time using graphql then it's probably an interesting and exciting new Endeavor I personally you know I've known of graphql and I've heard people talking about it but I've basically ignored it for the last few years until recently so I'm glad that I'm finally taking that step to pull graphql into my projects and get experience with it in the next episode we're going to figure out how we can add graphql to our back end so that we can use graphql in our front end with our back end so that way we are in control of the entire process beginning to end thank you so much for watching and stay tuned for the next video and be sure to subscribe what's going on everybody in this episode we are going to be doing absolutely nothing to do with react we're actually going to be setting up graphql on our back end but what would you expect more than that in a react series I mean let's be real so we are eventually going to connect to this graphql endpoint in probably the next episode or if you're lucky maybe even this episode so let's get started we are using Django I might do this with another back-end programming language in this series like I mentioned at the beginning of the series I'm just kind of going with the flow this time around just to see how it goes see what people are interested in and what you guys want to see so getting that feedback if you want to know a different programming language definitely drop it in a comment in the comment section below most likely it would be node if we decide to do another back end now as a quick note before you jump into this too much this is going to basically assume the prerequisite of already having models and data defined in the database if you need those Basics you can check out our earlier videos in the series where we set up Django and created a very basic rest API we're going to use the same models and same data that's already in our database so we don't have to recreate all of that so once we create our graphql endpoint we'll be able to just retrieve the data we already have so the goal is to get to a page like this for our back end where we can run this and get our customer data and be very specific about what kind of information we want right now we're not dealing with any nested data but we could add that in Fairly easily we could also grab a customer by name with customer by name and then passing in name being equal to slack as an example running that will get just that piece of data back and then I would like to take this data and display it on our react application instead of using the data from the SpaceX graphql endpoint that we used in the previous video we're going to use a tool called graphene and from their docs on this page you can go through the installation and basic tutorial where I'm going to basically go through the same stuff but instead of using the examples that they have here with their models for like this cookbook we're going to use our customer data which we defined in a previous video so if you want to get the code as it stands you can go to this repo and then go to the commits and you will want to start with the registration commit you can find all of the code right here or you can check out this commit hash so to start we're going to first be inside of our virtual environment so you have the venv over here and we're going to get a package so we'll say pip install graphene Dash Django now this is your first time it'll install I already went through this so requirement already satisfied is what shows up for me and then inside of settings we will need to add a few things so first down in our installed apps we will add it to this list so we'll just go in here and say graphene Dash Django and put a comma we also need to make sure Django contribs static files is in there which is required for graphical which we do have in the installed apps here so we should be good to go now we're also going to define a schema and we have to say where that location is we will Define that in our settings in the schema basically describes the structure of our data so this is step one before we can start asking for what we want so let's go back to our settings and we will Define where this schema is located I'm just going to place it here so we will create graphene and this is going to be assigned a dictionary with one key called schema and this is going to be assigned the value customers which is the name of our app so taking a look at our file structure we are going to be within this customer's app and inside of there we're going to have a schema file with a schema object so far so good all we need to do now is we need to Define that file so this is going to be kind of similar to how serializers allows us to create a rest API the schema file is going to do that same thing but for graphql so we'll go into customers and say new file and this will be called schema.py cool and this is what we're going to be working on for a few moments so I'll close out of that and here we'll say import graphene and from graphene underscore Django import Django object type and then we'll import our model which is going to be where the data comes from so from customers dot models import customer and now we will create a class called customer type this describes our data type and it's going to inherit from Django object type and inside of here we're going to have a nested class called meta which will have the model that we want called customer and the fields that we are interested in which I'm just going to have all of them displayed with two underscores all two underscores very similar again to the serializers it's going to follow the same exact style where we define a class and then a meta class for the model and the fields now we need to Define one more class in here and that is our query class so class query which will inherit from graphene dot object type also kind of off topic but whenever I install a new package I like to update the requirements.txt now inside here we're going to Define which endpoints we want so this is what was being typed in to this here so I have customer by name the one we used earlier was all customers so this is what we're going to Define and this one is not going to take anything passed in as an argument so let's try and Define that and it's going to be all customers and this is going to be graphene.list and pass in this class that we just created customer type and then we will create a function inside of this class so it's going to be indented right here resolve all customers and this will have two parameters to find here called root in info and all we're going to do is return all the customers so it'll say customer.objects.all oh that was a lot but we're getting pretty close inside of our settings we are referring to some schema object which we need to create and we will do that outside of this class definition so let's define that schema object and this is going to be an instance of graphene dot schema passing in our query class that we defined here so that is the structure and you can follow most of that from their documentation so it's not like I just made that up you know there is a system to this the last thing we do need to do is actually add the URL for the graphql endpoint so let's head over to urls.py and create a new path here and it's going to be graphql and the view that's going to be displayed after this we're actually going to import so from graphene underscorejango dot views import graph ql view so right there and that's the view we're going to render graphql View dot as View and then we can say that we want to use the graphical user interface so graph iql is set to true that should be everything if I'm not mistaken I think there is one issue we might run into and that will be shown when we run this application so if we say python manage py run server we'll get an error no module named graphene Django rip this is actually just a mistake on my part so settings.py this should be underscore Django that was not the error I was actually expecting it's this one cannot import name Force text from Django utils.encoding this has something to do with an incompatibility with Django 4 which we are using and this is really designed for Django 3 there was some change in the naming of things so we just need to change one thing in our settings to get this to work up at the top of our settings file this Force text was renamed to force stir so what we're going to do is just import that and then rename it as Force text so it's going to look like this and we will need to import Django so import Django so when we invoke Force text we're actually going to invoke this new Force stir and that fixes it and you see we're no longer getting an error in the terminal hopefully in newer versions you guys don't run into this problem shout out to this answer here which gave that solution now since our server is working we should be able to open our server and visit the graphql endpoint we get the graphical interface and you can hit this docs button up here in the corner and that's going to show your different endpoints so you can see we have the query which is the root of all queries and then we have the fields all customers and this is the type that it's expecting with these fields so that will help us build out what we want to query for so we will Design our query by first creating curly braces and then saying all customers and then inside of another set of curly braces we will say What fields we want which will be ID name and Industry no commas here and no colons either so once I got that we can hit run and we get all of our data back now again you can modify this removing any of these properties that you are not interested in and as mentioned we don't currently have nested data so I'm not able to show that but hopefully we'll add that here soon now all we'll do is have to take this path here and use that from our react application we're going to continue building on this in the next video so definitely stay tuned we're going to connect from the front end and the following video and then after that I want to talk a little bit about nested data and relationships really looking forward to the content that is coming and definitely would appreciate it if you give my channel a subscribe that's how I know you love this content as well as slapping the like button and watching through this series thank you so much for watching peace out and I'll see you in the next one foreign