Building a React App that Consumes a JSON API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
there we go so this was I've got the rails application up and running so I'm just running rails s we're not gonna spend too much time in the rails application today there we'll spend a little tiny bit of time in there because there's one more thing we have to do to get it ready for use with a react app but just a quick revisiting of the different endpoints that we have available to us so let me just close might close some of these endpoints I have here don't ask me again if I say that don't ask me again please there we are okay so remember the fact that we built this API and our things that we're working with is we have restaurants and we have dishes and those dishes have ingredients and so here's my restaurants JSON endpoint and when I fetch data there I get an array of restaurant objects each object giving me like an ID and a name and a description and so what I would like to do is I would like to build a react app Legation that hits this particular end point right here hits this restaurants JSON grabs the list of restaurants and displays the restaurant names and descriptions and then I also want to be able to work with the post endpoint which is connected to our create action so the get request of restaurants JSON goes to the index action and it loads up all of the data but a post request of the same endpoint is going to go to the create action and if we send in the body some JSON which is a restaurant representation which provides a name and a description we can create new restaurants so I want to be able to do that from my react top as well and if you you know if you had forgotten how to [Music] if you had sort of forgotten what endpoints you had available to you we could go to a local host here and go to /rael slash info that brings up all of our routes I can search for restaurant or even just the word rest and I can see what I was just talking about here a get request to my slash restaurants JSON goes to the index action and a post request of that same endpoint goes to the create and then we could you know we could work with the others but we're only today going to concern selves with those two all right closing that down I'm going to open up a nother terminal inside of my vs code I'm going to leave my rails folder and I've sort of gone up one folder from there and I'm gonna create my react app separately now there there is a way to create the react app within the rails project itself and so we could have the rails project and the react app that make it sort of live within the rails repository rails is set up with yarn and with you can pull react in you could have everything living in that one app and that would be what's called a mono repo we're sort of mono meaning one and repo is for the repository and so that style of development is is considered to be like a mono repo where your entire application lives in one repository I'm not going to go that route I'm going to try to preserve a little bit of separation here so rails is going to remain in its own repository and I'm going to use a tool called create react app to create a separate react app which is going to live in its own folder be its own git repository and it will even have its own web server associated with it so that it will run its own little server that will load up the react app and then that react app will hit our API at its different endpoint so let's see what we have to do to get that up and going we already have NPM and yarn installed in our wsl we installed that earlier on in the course right at the beginning and so what I'm going to do is I'm going to run a command called n px and what that will do is allow me to run this other command called create react app and if we if we go to our browser here we can search for create react app and we can see that there is a project and it is called create react app and it says set up a modern web app by running one command so we could make a sort of a homebrew react app we could just start our own folder we could start a project you know using yarn or MPN and start bringing in the different libraries that react creates and and bring in things like babble for transpiling and web Packer for the bundling of our source but we could spend a whole lot of time configuring our application and what create react app does is it sort of like what we type rails knew and the rails new command creates our entire rails file folder structure for us and sets up a bunch of conventions create react app does the exact same for for react there are a few of these style command-line tools to create react apps this one just tends to be one of the most popular ways of doing it but it's not the only way that you would start off a react application it just is just the most popular these days and so if we go to the QuickStart it's got what I was just about to type in myself the MPX create react app and then the name of the app and so I'm gonna call it restaurant app and I will hit enter so that's going to fetch create react app as a module and run it so it's gonna get the latest version of create react app off of the NPM package system it's going to run that it's going to create a folder for us and effectively it's going to do just like I said what the rails new does but in this order the JavaScript world so when we first run rails new it sets up our project as a git repository and then it gives us a gem file and it runs bundle install will create react app creates a folder sets it up as a git repository and it gives us a package JSON file which is the JavaScript equivalent of that gem file and then it's gonna run yarn install for us and it's installing all of the dependencies so well that is happening I'm going to show us one other thing in the rails application that we need to set up the react as I mentioned earlier is going to run its own server we have rails right now running on localhost 3000 that's actually the default for the react application as well so when this finishes running we're gonna change create react apps configuration to run create react app on a different port I'm gonna have it run on port 30 30 instead of 3,000 and then we want the JavaScript in the create react app to be able to hit our endpoint the thing is though is that most browsers all modern browsers I guess they include something called cores and servers support this as well cores that's an acronym cor s4 cross-origin resource sharing and by default most web servers do not permit cores and what that means is they do not permit JavaScript to make a request to that server unless the JavaScript was served out at the Zak same domain and so if I have for example on my domain stung I comm if I had an API up there and I did not support CORS then that API could only be accessed by JavaScript that was running off of and being served up by stun I comm it could not come from a different origin the thing that we're trying to do though is to have two separate products that could potentially be on different origins and there they are going to be on different origins because we're running them on different ports and so we have to configure cross-origin resource sharing in rails to make rails able to take the requests otherwise rails will just deny the request our react app will try to hit the the json endpoint and the server will just be like no this is against the the course policy you cannot access this api so how did i set that up in in rails well i used to gem a handy gem called rack cours rails itself is built on a lot of different open-source projects and the HTTP system inside of rails is built on something called rack and rack supports plugins that are called middleware and they give you the ability to sort of change how the rack system works with HTTP requests and so rack Korres is middleware for handling cross-origin resource sharing or cores and that says which makes cross origin origin Ajax possible and Ajax being sort of the older AK UNAM that you used to use for JavaScript making asynchronous sort of requests and so to get that going in my rails app I went into my gem file and in my gem file around line 33 I added in gem rack - course I then disabled my server so I went in and I control seed my server I ran bundle install that pulled in the rack cores app into my application and then on the rack course website or even just that I guess it's just the github repo it gives you a little bit of a snippet of code that it tells you that needs to go into your rails config application dot RB file and it specifically just this little bit of code that I've highlighted you don't need the surrounding code it also gives cold code for like very old versions of rails we only need this one right here it says rails 5 but it's really really been above and so it's the line here that starts with config middleware insert before and it goes all the way down to this end so we need to copy and paste that and we need to put it in our config application RB file so I'm in my config folder my application RB I've already put mine into here but you can see I've pasted it in right here so I pasted it inside of the module restaurants and the class application this is actually this class right here is the main class for our entire rails app we don't often touch this file specifically but to insert middleware specifically rack middleware we have to go to this application and we're just pasting these lines in right here so we're asking the config object of this application to go to the middleware subsystem insert before everything so right insert at the very beginning of all middleware rack cores and then we apply some white lists which origins are we going to allow requests from so here we could either put a list of origins that are considered to be friendly to us we might say ok well you know I know this particular domain is where I'm going to be hosting my code that's where I want to that's where I want to allow in our case we're just sort of white listing everything we're saying that rockers all origins all resources and in fact all headers oops don't want to wreck my sit up there so that's just what we pasted directly in there and that's also what would be set up a similar thing would be set up on any website that you've been able to you know access by way of JavaScript so in web dev 2 if you did some JavaScript Ajax work with the city of Winnipeg open data portal that's allowable because of the fact that that open data portal has a course policy that white lists all origins all resources and all method headers and etc so once that's in there I can start my rails server back up and then that's the the last of what we'll need to configure for the rails server today okay it's running again I will just go to postman and just make sure that nothing is broken I'll just request my index endpoint everything looks good meanwhile in my other terminal here I've got the create react app has finished its work I'm going to navigate to the restaurant - app folder that was made there we can look at what's in this folder and in fact I can add this folder by right-clicking in my Explorer over here I can add folder to my workspace I'll pick the restaurant app and say ok we've got a node modules folder in here that makes sense because that this is a react app so it's gonna bring down a bunch of node modules and you can see in there there are a bunch of node modules you never really have to go peek around inside of that folder if your application ever starts acting weird ways sometimes the the solution is just to completely delete that node modules folder and rerun yarn install from the command line and it'll just repopulate that folder for you you can see that our project is set up as a git repository if I do get status you can see it's already and get repo so we don't have to do get in it here we have a git ignore file setup for us which is ignoring that node modules folder so those modules will not be checked in to our repository just because they can be recreated when we run yarn install we have this package JSON file and an associated yarn lock file which is sort of the same as you know our gem file and our gem file lock and in here you can see we have some dependencies like react react Dom and react scripts and then we have this scripts area which actually tells us different little commands that we can run and so from the command line I can run yarn start or a yarn build or yarn test or yarn eject and so I'm gonna run yarn start which is going to start a development server it's gonna take the application which lives in this source folder and make it available on a particular port if I ran build it would actually take my application and into a build folder it would package up all of the files that I could then put up on a server for deployment but I don't want to be in deployment mode right now I want to be in development mode so yarn start is gonna get me into development mode so I'm gonna run that we're gonna see that there's a problem with this when I run yarn start it opens up my browser at localhost 3000 and we see our rails message and the reason that's happening is by default yarn tries to run on port 3000 just like our rail server that's not what we want right we want it to run on a different server so the way that react scripts works around the server is we could set the port that we want the server to use inside of a OS environment variable the other way of doing it is I'm going to add a new file to my react app right here so i just right-clicked on restaurant app new file and it's going to be a dot env env file en be standing for environment and it's a dot file so it's a hidden file in our in our system so if I just did an LS we would not see it here but it is visible in our Explorer over to the left there and inside of it I'm just gonna say port equals and then whatever I want the port to be so I could make it port 8000 I could make it port 3 1 3 3 7 I'm just gonna make it port 30 30 so we're gonna have rails up on port 3000 and our react server running on port 30 30 so if I save that dot env and I run yarn start look at that you get the react icon spinning around nicely it tells me to edit source app das saved to reload and a link to the official react document and so things are working if you are trying to work along with me did you have any issues here as anyone run into anything that has prevented them from getting to this thing right here being able to run yarn start and have the browser pop up localhost 3030 and see this little thing let me know in the chat if anything is stopping you otherwise I'm going to hop into the folder and file that it just mentioned so it said source app dot j s that's here there's a source folder there's also a public folder here we can look in what's in these various folders in the public folder the the file that we'd most likely be working with in here is the index.html this is the HTML file into which our react app will be installed we look right here there is a div with an ID of root that's where our react app is going to be injected right there so if I removed that and I have REE and I went back over to my server it gives me an error saying the target container is not a Dom element meaning it it tried to find that Dom element the div with an ID of root so that it could inject the react app and it didn't work the one thing that you can notice though it's like anytime I save my file the browser code automatically reloads and so if I bring that back in I save my index.html and I go back over to the browser it's running again so we'll be back into this index.html a little bit later to load up some web fonts up in the head of the document but we'll also go over into this source folder here the main application that launches our react APIs inside of this index JSON file or sorry index dot JSP react is being imported from the react library react Dom is being imported here but the key thing here is that we are going to react Dom and we are rendering an app component this capital a PP app component right here and where are we rendering it to we're going to the document.getelementbyid route that is what's finding this div with an ID of route and injecting our app there and then what is this app well it's being imported from another file specifically this one right here this app j/s so if you look here where it says learn react I could add some exclamation marks at the end of that I could go back to my browser and the exclamation marks are present right here where it says edit SCR app JSON and save and reload that's this stuff right here right so I could change that to hello class save that come back so we've got live reloading every time I change this file it changes here we just have some stuff in here that just sort of comes in by default and I'm gonna remove it all I'm gonna leave the div with the class name of app and I'm gonna remove everything else inside of it we're at a clean slate this is where we can start creating our react application from our clean slate right here in fact even I can get rid of this line too which is importing logo that's the SVG file which is the the react logo that was spinning around we don't need that anymore I'll leave this app dot CSS file in for now but we will you know we will be able to take that out later we're gonna apply some styling separate on our own later but we'll leave that in for now okay so what do we have here we have our react app which is this app function right here it's a functional component it is returning so if you remember back to our lecture on react when we have a functional component whatever gets returned is going to be JSX which is markup HTML markup inside of our JavaScript that's what's being returned and that is basically what our component is so if I put a paragraph tag in here and I put back hello world that appears inside of here anything we return from this function is what our react app is going to be the other thing that I have installed inside of my browser is the react developer tools extension so if you're using Chrome you'll want to search for react developer tools Chrome if you're using Firefox you'll want to search for reactive elevator tools Firefox and you'll want to install that extension I just went react react the Velo / tools I use Firefox so I just went and found the Firefox extension and installed it it tells me okay this page is using a development build of react that's good I cannot now go to my dev tools with a ctrl shift insert these are my browser dev tools right this is where I have my inspector and my console and my network tab but notice there are two new tabs here one called components and one called profiler profilers for doing things like speed tests seeing and you know which if we had a very complicated react app that was sort of a very heavily nested lots of different components within a components we could profile the speed of these various components and see if any of them were causing slowdowns or how we could fix that and then we also have this components view and we just have a single component in our application right now it's this app component and it currently doesn't have any data associated with it at all it's just very basic so as we build it up we could come back in here and we could sort of see more information about it but for most of what we be doing today this will be a little bit boring because we're really just working with a single component I'm gonna try to keep things very simple and I'm not even going to while they're breaking things out into separate components so I'm not gonna be totally following reactive best practices just to keep things simple I'm gonna be doing all my work inside of a single component alright so I have that installed before we actually get to coding what else do I have installed well I have some extensions installed in vs code that make working with react a little bit nicer what are some of those extensions they are the yes lint extension by Derrick boomer so if you do a search for es lint by Derrick Ballmer and I also have prettier by Esben Peterson those two things yes lint and prettier they do the job of what Robocop was doing for us in the Ruby world so one of the things that ruble cop was doing for us is it was making sure that we were following the Ruby community conventions and when we strayed from those conventions it would put underlines in our code to allow us to know that we were doing something that could be fixed and we could hover over those things and get some you know some debugging information I wonder if I can force the issue here we'll see it later on they'll be times one won't see little squiggly underlines and it'll be es Lent telling me that I'm doing something that sort of goes beyond conventions or maybe something that could be a trigger of a bug and so that is what he has lint does for us prettier is a code formatter so that was the other thing that ruble cop was doing for us is that on save robocop would reform at our code according to again community conventions and prettier does that for javascript so it automatically format so you can see here prettier in action if I sort of add extra space to this paragraph right I've put hello world on its own line if I save boom it puts it on one line for me and so that's prettier saying like nope to save room we can have that all in one line it's also going to apply formatting to my JavaScript it's going to if I accidentally leave off something like a semicolon so I say I forgot both of those semicolons up on line 1 and line 2 there it's gonna put them in now I can't actually remember if I had to also install like command line tools for both eslint and prettier as well I think I may have and I would have installed them using yarn and so let me just quickly yarn install es lint to install eslint globally which is what we want I don't want MPM install I want yarn install go to the official Docs and it looks like from the command line we would type yarn add yes lint - - dev meaning it's it's not to do with the the actual code that we're writing it's more of a development plug-in and so you may want to do that from your terminal right now make sure you're inside of your restaurant app and you would do yarn add yes lint - - dev and then there's also prettier prettier search for that and it'll be the same kind of thing yarn add prettier - - dev - docks exact I don't know what the exact does or you can also add it globally so when you do a - dab it it adds it to the existing project but as a dev dependency so it'll end up in this projects package JSON if you add it globally it's going to stash it away inside of where yarn has been installed not in the node modules in this particular folder you can try doing this first one so yarn add per year - - - - exact with those two things in place with es lint in place and with prettier in place from yarn and these extensions in place you'll get sort of the same kind of protections that I have running in mind let's see if there's any other looks like that is the extent of the Java Script specific stuff that I have running okay so with that running we are good to go we want to make this react app hit our JSON endpoint we want to be able to hit this localhost three thousand restaurants JSON so I'm gonna copy and paste not URL copy and paste it I want to be able to get this array because that's what this is it's square brace right here so it's an array of objects and then I want to be able to loop over those objects and for each one I want to be able to print out the name and the description of the restaurant that we are working with and I want to do that from my react application and so the question is what do I need to do to do that well many get in this hello world in order to grab these restaurants and be able to save them I need to add some state to my component and the style of state that we first explored when we looked at react was using hooks and so I'm gonna set up a hook au State hook and I'm gonna stay constant and I'm going to make a getter and a setter for my restaurants State well that should be restaurants plural this is gonna be the state that stores my array of restaurants that is coming to us from the API I'm gonna use the use state hook and I'm going to provide to that hook a default of an empty array you state here you can see now already pretty s lint is kicking in as telling me some things it's saying like restaurants is declared but never read and and set restaurants it's assigned a value but never used those are orange underlined or yellow underlined meaning they're they're warnings you state here is straight up of an error you state is not defined so I need to go pull that in so up here not only do I want to import react from the react library I also want to bring in use state and so I put that inside of curly braces because I am destructuring that out of the react library you can see my crew my little red underline has gone away with you state now that sets up my state I now need to actually make a request to fetch it and we need another hook for that which is the use effect hook use effect and so maybe even before doing that let's just let's just keep things a little bit simple first to keep things a little bit simple first inside of this curly brace restaurants here I'm gonna just manually put in a hash where I have a name property I put it in as coops don't don't do that on me I'll put it in similar to a little bit of JSON I'll say it has a name and I'll say the Lutton noodles and it has a description description and I'll say Wally glutton makes tasty noodles and then I will put in another copy and paste another object and this one will be Santa Lucia Pizza my favorite pizza I will eat all the pizza so that's gonna create this restaurants setter for me and give it some initial state and I'm just sort of mocking the data out so I just sort of fake data so that I don't even get into the use effects just yet and then inside of my JSX I'm going to loop over my restaurants and display them one by one the name and then the the description as well so inside of my JSX to in to embed some JavaScript inside of there I use my moustache braces and I'm gonna say restaurants dot map that's gonna visit every single one of those restaurants it'll temporarily call each one of them rest or rot singular and it will then run a little bit of code here what do I want I want it to create a let's just say a paragraph tag where I take that restaurant and I display its name let me just see if that did what I wanted it to do over here in my obligation very close but I forgot the curly braces so you can see it's it's trying to display two things but it's literally typing out restaurant name because I forgot the moustache braces around that so it's just assuming that that's just literal text that I want in there and so I got to put those moustache braces around that to indicate that it is JavaScript that needs to be executed lo and behold UNC right over here there is my collection noodles and my Santa Lucia Pizza one after the other in their own paragraph tags I could change that up and I could say well let's put them inside of each ones and let's put them in a div as a sort of a placeholder and I will put a paragraph in there to put the restaurant description restaurant dot description and check it out over here I have a glutton noodles a Wally go out and make some tasty noodles I've got my pizza that data is coming to us directly from this default state that I set up and then down here I'm going to the restaurants getter that I set up right here and I'm getting that state I'm looping over it with my map and for each restaurant I am creating a div that has a nested h1 and a nested paragraph tag and then I am executing this name and description inside of there to get the name in the description out of each restaurant so that's all well and good if I just had some static data like I do right in my application but that's not totally what we want right we actually want to fetch that data so now that that's going I'll bring that state back to an empty array and I will bring in the use well let's just just say let's just say it's time for a git commit here yeah get status yeah a D&V get commit - em setting a new port that doesn't conflict with Rails and then we still have my app here and I commit and I say state-established for restaurants with a use the state hook and a simple loop over the loop to display great now I will come in here and it's time to use another hook and the hook that we use when we are working with a react app that we want to pull in some data from a fetch request is going to be the use effect hook there it is use effect and so I'm going to run this use effect hook I'm gonna run it right here underneath my youth State but above my return I'm gonna say use effect and the first argument of use effect that's going to be a stabby arrow javascript closure or anonymous function that's what this is right here and then the second argument is just going to be my dependency list and when I'm using use effect and I only wanted to trigger once at the mounting of this application well then I just pass in an a empty array as the second argument and that indicates that there we don't want to call this use effects repeatedly based on any dependencies that we have in our component we just want to call it once when the component mounts and then what we actually want to do when we call it once when the component mounts is going to be what's going to be inside of this anonymous function or closure that we're sitting up here with the fat arrow syntax so I'm going to expand that to multiple lines and I'm gonna put the request in here it's a fetch request so remember that is how we fetch data using HTTP in JavaScript we make a fetch request we're going to go to a particular endpoint as a string we're going to HTTP colon slash slash we're going to our localhost 3000 that's our rail server and we're going to our restaurants dot and JSON the fetch API when you send it a string like that a URL in a string it's going to return to you immediately a promise and remember that means like anytime we get a promise back it means that something is happening asynchronously in the background for us and we can set up what to do when that promise actually resolves when when it when it completes and so the way I do that is I say then so what to do after the fetch actually completes and if we don't pass any other properties to fetch it's just gonna default to a get request so if fetch is going to return to us a promise and it's saying to us I promise after completing my fetch request to this URL that I will trigger whatever you put in this then and so we're gonna get the response back and we're going to establish another fat arrow function and what we want to do with that response the response comes back to us the response is JSON but it comes back to us as a string so we need to deserialize that response and we do that with response dot JSON there's a method on the response that will D serial the response and this is uh I find this a little bit awkward because the JSON method also returns a promise so it doesn't execute immediately it executes asynchronously and the reason is is that there's a chance that we just fetched a whole bunch of JSON so we don't want to block the main thread the main browser thread and so JSON is going to do that D serialization in the background on the different thread and it's just going to return to us a promise saying I promise once I've DC realized this JSON to resolve this promise and then and over to use some data and once that data has resolved I will call this anonymous function and do something with it so we actually have a promise inside of a promise here I think I could actually chain them one after another but I don't I don't mind I'm only gonna do one more line here so I don't mind that this sort of the double nesting of the promise here and then what do I actually want to do with this data what is this data well this data is actually our array of restaurants right because that's what the restaurants JSON endpoint returns to us it returns to us an array of restaurants and so I'm going to use my setter set restaurants and I'm gonna pass it the data and so again looking at all that Yusef X is going to set this up so that when our component first mounts this anonymous function is going to run the one thing we do in this anonymous function is we fire off a get request via fetch that returns a promise to us which we say well when that promise resolves I want to take the response and I want to deserialize its JSON and when that dearest DC realization is done I want to take that data and I want to set it as the restaurants so I'm gonna hit save here gotta head over to my browser and check it out there are all of the restaurants their names their descriptions the same ones that we saw when we made our get request inside of postman all right the very first of those was golden spoon and it starts with the description to ensure that east each guest receives prompt professional friendly and courteous service well that's the same thing here golden spoon same description so we've hit the end point that is working that makes us nice and happy and you can see there's not a whole lot of code that's required right we had already set up our state ahead of time and we had already set up this mapping so that when there were restaurants we would iterate over them and create a whole bunch of divs and every Dib would have an h1 and a paragraph for the name and the description of the restaurant so we had established that already this just goes and fetches the data we can actually even see this data being returned if we go into our dev tools so I'm going to [Music] control shift it's telling me each child unless should have unique key I can fix that in a second so sometimes es lint gives us little warnings in the console as well as the browser you can see there's no browser warnings here but I'm getting a warning down here saying each child in a list should have a unique key property that's that's something that is easily solved what it's worried about is we're making a list of things here and the way that react operates is it wants a unique identifier on each one of those things so that if the data changes because react is reactive it wants to be able to know which of the items in the list it needs to change any and it can do that much easier if we give it a unique key and so that's not a problem we actually have a unique key with the data that we are working with because we have the primary key from the database right because so for each one of these objects we have a unique identifier 1 2 3 etc etc and so we're gonna use that and so I'm just gonna set that up right here in this div I'm gonna say key equals restaurant dot ID just adding that to the div that I'm mapping over and back over here that error message has now gone away based on what the user sees I mean that is something that is not visible at all to the user that's just something that react itself wants so that it can work more efficiently with the data that's on the screen it wanted a unique identifier so we gave it a key the thing that I wanted to show by having the dev tools up is in the network tab we can actually see all of the requests that go into this particular page I can even hit control R and reload it and if we wanted to just look at this one here the actual fetch request that we made in the network tab we can if you see here below where my mouse is moving we can filter the types of requests that come back over the network and so when we're debugging something that's using JavaScript specifically using fetch we don't really care about all of the things that are coming down the pipe we only really want to care about xhr requests and so xhr is just another way of saying like javascript making a a synchronous requests for API data and so I can filter just to that you can see there was a single request that came in and that was in fact our request to localhost three thousand restaurants dot JSON you can see it got a status code of 304 we would have seen a status code of 200 the very first time we made that request and then after that that request would actually be cashed and so you can see here status code three or four not modified so the the server is telling us like that data hasn't been modified since the last time that you fetched it so you can use a cached version of that thing but what is the actual response well there it is there's our JSON data the same data that we saw in postman so that's just a quick place to to look if you're ever having issues with fetch requests and you don't know if the data actually came along the way you wanted it to or if you maybe we're getting a status code that you weren't expecting that's how to find out about it you filter for xhr you see the status code there and then you can click on it and you can actually see like the headers that went into that response if there were any parameters but the one that we're concerned here is the actual payload or the response itself okay so that is that is one thing I'd say let's take a little bit of a break maybe just a five-minute break so that we can stand up and we can stretch and we can think about what we've done so far and so I'm gonna pause the video right now and what do I do that I do that over here yeah all right the screen is recording so as I said I want to do a little bit of yeah another end point I want to hit another end point and for that I need so at this point in an ordinary app we probably start to break things out into separate components but I'm not going to do that I'm gonna keep everything in one just to keep things simple today so I'm gonna I'm gonna add some stuff right into the existing component I'm also gonna add some new state here I want to be able to add a new restaurant and a new description to my API and so I want to set up some States up at the top here I'm going to set up a state for new name and a set new name and I'll say use state and I'll give it a default value of a empty string and I will also new description and a set new description and that'll also be a used State hook for an empty string and I'm going to create those here inside of my application I'm just gonna put them inside of a div and by them I mean I need something to bind this data to I want somewhere for the user to be able to put in both a new name and a new description and so I'm gonna create those as inputs and I will bind some data to them so that's gonna look a little bit like this I'm gonna say input and I'm going to say that on chain of this input and I'm just gonna put a anonymous function right in here a little stab URL function right in here that called set new name when on change fighters I get an event the event has an event target that is this input here and the input has a value and so that's that's what I want to do right like that and I'm gonna copy and paste that line I'm gonna do the same thing for set new description so that anytime the one of these two inputs changes I put a restaurant name in here and a description here as I am typing that data in it's updating the new name and the new description state using the set new name and the set new description setters on change and maybe just to make this a little bit more obvious I'll put a placeholder in and I will say restaurant named as the placeholder and placeholder description and so you can see we've got those placeholders up there now again I'm not making anything pretty right now we're gonna add in some styling later so this doesn't look very nice at the moment but it's okay I'm also gonna put a button in it's gonna be a submit button or like create new restaurant button there's my button create new restaurant basically what I want to do with that button is I want to give it a non click handler so that it will actually add the restaurant by hitting the correct end point and so up here way up here I'll do it right below my use effect here I will set up a Const reference to add restaurant and I will just drop in an anonymous function and assign it to that address Toronto will give it any content just yet maybe I will give it like a console dot log adding restaurant restaurant and then that's that's it that's all I'll give it right now I can even put in a bit more debugging information I could I could output the the setters the new name and the new description a little bit of debug information there and then I'm gonna make it so that this button down here has an on click so I'll say on click equals equals and then what do I do for that I think I just need to specify the actual name of my function yeah I think that's what I do and restaurant like so so now every time I click this button it's gonna take the current state of new name and new description and echo those out to my console and those will be coming from whatever I have in my inputs above so let's head on over here let's open up the consoles that we can see it here it is restaurant name and description those are just placeholders so currently there's nothing in there so if I clicked create new restaurant I get adding restaurant and two empty strings and so here I could say like my noodle house Wally's noodle house and my description is yummy noodles and then I can click this create new restaurant again boom look at that adding restaurant Wally's noodle house yummy noodles okay that form stuff seems to be working I now actually want to put the correct code in to add restaurant and that's when I want to hit another end point let's just refresh our memory about how that endpoint works I'm over back in postman this endpoint right here which is the restaurants JSON endpoint if I do a post request to it and I have the content-type setup as application JSON and in the body payload I drop in a description of a restaurant with a name and a description nested within it that should create that restaurant for me so I want to recreate this same thing but from a fetch request right so I need to do a fetch post to that endpoint and then I need to create some JSON that looks just like this a JSON object with a restaurant key that has a key of another JSON object with a name and a description key and then I want that name in the description to actually come from that state we just set up so let's do that let's remove those console dot log scuzz we know that thing is actually happening and we're gonna say we need a fetch request that fetch request is going to go to the same endpoint we were going to before local host 3000 restaurants dot JSON but it's more than just that I'm gonna pass in what's called a options hash here as the second argument so here we just had one argument it was just the URL for our fetch request this one we've got a second argument and in that second argument I can give it give fetch a few more details about what I want to be sent along with this request I want the method to be a post okay and I want some headers to be sent along with the post specifically I want to set the content type type header to be application slash JSON and then I'm leaving to go further just to prevent any possible character encoding issues I'm gonna put a semicolon in there and specify that the char set that I'm using is utf-8 which is sort of the universal char set that we use on the web I've just run into lots of character encoding issues on the web before so it's sort of I feel like it's important to to mention that when we're coming and the data is coming from a browser and we might want to support lots of different languages so I set up the method the headers another comma and then the body right I have to set this thing up right he like this this little bit of data so the body is going to be and now this is a little bit awkward because to send the body as a payload it needs to be a string but I want to build the data up as a JavaScript object and then I'll need to convert it to a string to send over the wire but we just so happen to have a lovely little tool built into the browser for doing just that which is JSON dot and my favorite method name of them all stringify so I'm gonna say stringify this object for me and what is the object that I want string a find okay also getting a curly underline there because I think I missed a comma yeah and so what do I want to stringify an object that has a restaurant key that points to another object that object has a name key that's gonna point to some name and a description key that's gonna point to some description but what it actually wants to send along is the new name and the new description that we've set up with our state so reviewing fetch request to our endpoint with an options hash that sets up the fact that this is a post method we've got some headers on it and we've got a body payload which is the stringify version of this object right here in fact this object here and that object packages up the new name and the new description of the state that we bound to these inputs here in here so we should be able to put some data in here and click that the thing though is we probably want to respond to that in some way and so I'm going to this is the end of my fetch right here remember fetch always returns a promise and so I'm going to say then take the response and take that response and deserialize the JSON payload that you just got back and then what do we do oh I need my thing like that the deserialize response what is the response to this thing well postman tells us that if we send this data so here I'll say tester and then the description is Mik Bester I'll need a capital B there that's important send that to Rails what do we get back we actually get a JSON representation of the new object that was created in the rails back-end that has a name and a description and the created and updated at so this is the response that our create endpoint is gonna send back to us it's gonna send back a JSON object than it is our actual restaurant and so that's what's coming back to us here so we get back after deserializing that response we actually get back the new restaurant and what we would like to do after doing that oh yeah let me just do this for a second what we would like to do after we get that response back is we would like to add that restaurant to the end of our list right we'd like to add that restaurant back to the end of our list and so what do we need to do to do that well we need to take that new restaurant set up a little stabby arrow make use of set restaurants here and so that's here set restaurants and then I'm gonna use a sort of a newish property of JavaScript or a newish bit of syntax of JavaScript which is the spread operator so set restaurants here sets our array of restaurants if we just set our restaurants to our getter restaurants sorry restaurants plural it would leave it alone right it just be like it would take the existing restaurants and set it to itself that's not what we want what I can do though is I can inside of an array I can use the spread operator dot dot dot and you can think of it that's going on spreading that data out and so it's like it takes all that data as if it takes it out of the array and spreads it into the new array and then I can put a comma and I can put the new restaurant right at the end there so take the existing restaurants spread them at the front of that array and then at the very end of that array put the new restaurant in and then set our restaurant state with that and that's a very sort of new JavaScript style way of adding one restaurant to the end of our existing array and it's done in an immutable way because we're not actually modifying the restaurants variable itself we're using set restaurant using the existing data spreading it out and then putting a new restaurant at the very end so let's see if that actually works this is the moment of truth so the moment of truth where do where do I go I've got all these sorts of things open there okay here it is I'm gonna keep my console open here just to see maybe even keep the network tab open reload just to trigger that see if we're filtering for it that's X H our request we should see one fire off should see a post request fire off I'm going to say from browser hello restaurants or odds I'm gonna click this i'ma cross my fingers clickety clack there's a post it went through got a to old one back is that what we were getting back from postman yeah - oh one is the created status code so that's you know that's what we were hoping for if we look at the response it is the the correct thing that we were expecting it is the JSON payload of the new restaurant it's at primary key 16 in our database the console doesn't have any errors so that we're happy about that and if we scroll down to the end of this list from browser hello restaurant and so we can now add as many restaurants as we want and we could also do things like okay look that still in there and that's still in there we might want to clear those things out when we create a new restaurant that said that is what I wanted to show off in terms of having react use the endpoints that we had set up with rails I want to show one more thing quickly here but I'm not going to code it out I'm just gonna go right to the final state and then just describe the the the code that is present and so I'm going to go to my terminal here where I am running my react app and I'm gonna kill that and I am going to go to I've got a separate react out right here another one it looks similar cuz it is it's the the same basic application but I've added something to it and I'll show you what I added material.you I react components for faster and easier web development build your own design system or start with material design and if we scroll down here it tells us that we could install this in our application at the command line by running NPM install at material - UI core we aren't using NPN for our project we're using yarn so we would at the command prompt so we'd say yarn install and at material - UI - slash forward slash core oh yes thank you it's ad awesome and so that's what we would type in to add it to yarn that would add it to the package.json it would also at that point go and download and install all the associated dependencies and then it says also we need to load the Roboto font and so we would copy and paste this link here and we would paste that into the index and you can see that I've done that right here so that's a web font so it's a link that's pulling up a style sheet with an href and it's actually pulling in a web font from the google fonts and it's the Roboto font which is Google's default font for material design with those two things in place we would now be able to which I gotta make sure I've got the right that I've got the right application up on the screen yeah this is the one with those two things in place I could now start adding the components that belong to this material UI core and what do I mean by that what do I mean by adding these components here is an example right here where they say in a react application you can go to the mature you i-corps that you've added to your project and then this example they are importing a button component and then in their JSX they are using this button giving it a primary color giving it some content it's going to be not just a regular old button like I was using in my application but it's going to be a button that comes pre styled with material design guidelines if we go to the component list here and we go to buttons we can see the different kinds of pretty buttons that this component framework gives us access to and the different kinds of ways that we would set those up so here button variant contained with the text default that's what gets us this one right here button very it contained color primary it says that one etc etc we can set up all different kinds of buttons buttons that sort of look more like links until we hover over them outlined buttons small medium and large buttons we have all sorts of components so this can put is a component framework just like boma just like bootstrap but it's not just giving us like normally when we're working with bootstrap or boma we're adding the styles by like adding specific chunks of markup to our HTML and then styling with provided styles that we add to that markup with this style of component library that we're pulling in here the components come pre styled for us and we just have to use them instead of using HTML inside of our JSX we can use these components there is a grid system that we can make use of you can set up a particular spacing of your grid how sort of spaced out your grid should be you can sort of specify how how many units particular entities within your grid take up the grid is broken up into twelve units and then you can say well I want something to take up all twelve of them or I want a grid where each element takes up six and six or three and three and you can even change what those are based on the screen size so you could say like when you're on a mobile phone when I want each grid element to take up all 12 so that each element is stacked one above the other but on a desktop screen you want them stacked up side-by-side maybe three in a row so you can set up work with the grid system it's a very nice grid system they've put into place it gives us things like dialog modal's and so if I click on this button nice little pop-up right a little pop up like that or like a little alert like this agree and disagree I'm gonna now hop over to this application I'm gonna run it I'm gonna gonna run a yarn start here and we're gonna see the same application that we just built but now it's gonna be styled with material design styling rather than just plain old HTML which is what we had before so this is what we originally had before sort of plain looking little inputs up above and then the content just sort of centered like so here's the app up and running with material design and so I'm using cards for each one of the restaurants the restaurant names are in card headers I wrote a little snippet of JavaScript to use regular expressions to take out the first letter of every word in the names of the restaurants and I'm using that beside the names like a little avatar there is the description or at least the start of a description I wrote a little bit of JavaScript to truncate it past a certain number of words there's a learn more button that currently doesn't do anything yet but it just is there maybe that would eventually take us to a different page and then there is this new restaurant button that pops up a modal like that where I can type in a restaurant name and see pants form this is the form that I made with material UI period oops what have I done here period and now I can click add point I can go down to the bottom here and there is the new added element so based on like the code itself like the the business logic of the code itself is no different it's still doing exactly the same thing right it's still going to my index end point it's fetching all of my restaurants and I'm looping over them I'm still going to that create end point and I'm posting this data there it just looks a lot nicer because I'm using the material UI styling and what that looks like here at the top of my application I've gone to that material UI and I've imported a whole bunch of the components that I want to use like one called avatar and button and card and card actions so I did some research I figured out all the ones that I wanted to use and then down below inside of my JSX I'm using those things I'm using those particular buttons and grids and card helpers and all those kind of things to build up my JSX instead of using HTML and then they just come nice and pre styled for me but the actual core logic here is really no different right here is where I'm looping over my restaurants I just so happened though to be looping over the restaurants inside of a grid container where I've set up some spacing and then what am i creating for each restaurant well I'm creating a grid element I set up the grid sizing so I'm saying like on a small screen this grid element should take up all 12 units so that it should take up everything but on a really large screen it should only take up 3 units so that would be like 4 of them side-by-side and what do I have at that each grid position I have a card and that card includes a card header and an avatar so I'm sort of building up with this design system that's pre-built for me and I don't have to write any CSS because these things are pre styled now there's a few places where I could inject CSS to do a little bit of extra work for me so for example this avatar right here that is these circles and so if I wanted to I could put a little bit of inline CSS here I could say background color and I could set up a flavor of red something like that yo why you're not working for me style background color oh they just stick it a little time took a little delay and now I have my avatars of red notice this is not actually completely CSS this is actually just a little bit of JavaScript sort of masquerading as CSS right background camelcase color this is really just a little bit of JSON you can see I even needed to put the color in quotes so that's not actual CSS that I'm putting in here but it's gonna be converted into CSS and and sent along to this avatar for use when it gets created inside of the application but it's it's a way of customizing the components that I am working with and so I've I've basically built this whole thing up you can see though it got a little bit out of control this is what I mean about the fact that I'm not following best practices here everything my entire application the cards this button even this dialog box they are all inside of one giant component and the next thing I would do with this application is I would refactor it to create these as separate components those would each be put into their own separate file in this source I would then import those components up here and I would use them as sort of sub components or child components within this main component so that would sort of be the next step so the I'm not going to go into more detail about how I built this what I will do is with the other section I did a slightly different version of this lecture where I focused a little bit more on this material UI library and I actually showed how to build some of this up I went and I built built the whole sort of grid system up so like this part of it and then the part that I never got to with the other section is I showed them the the form here but I never actually built with them the fetch code to add the restaurant so I did a little bit of a different take on the lecture because when I did the lecture with the other group at the end of it a lot of students said that the material had been very heavy and that I had covered a lot and that they were I think they were feeling a little bit confused and so you might be feeling the same right now because I did cover a lot right this is we're sort of now in that domain of the full stack right where we're working with the backend API we're working with the front-end rails there's a lot to it but if you do want to see how I went and built up some of this stuff with the component framework I will give you a link to not only the recorded version of this lecture but also the recorded version of the lecture I did with the other section and you could dive into that and sort of maybe fast-forward to the point where you could see me building up at this grid and I sort of go through the whole thing of like adding material UI and bringing in some of these components with import statements and then using them inside here and so if you if you feel like that's something that you want to do you can the other thing I will mention at this point is this week has been focusing on rails as an API and then today we're looking at react specifically but that does not mean that you have to use react in your project in fact historically the majority of students do not use a JavaScript component framework in their project they just build a project with rails alone and they don't get the marks for using react and that's fine there's tons of marks available in the product and the project and you can build a very nice project without using react and in fact if you do use react it is a lot more work there's a lot more that you're going to have to do there's a lot more you're gonna have to learn on your own there's already some stuff that you have to learn on your own in the project one of those things being authentication and logins with devise but there's even more that you're gonna have to learn on your own when you are using a component library like react so that's not to scare you away from it but I would say if you don't have previous experience with JavaScript component frameworks you might not want to go down that route and you know I did post on learn a few example projects right one of them being the example project that was built that only used rails and the other one was one that I built with making use of view this one here is the one that is rails only and it still is quite slick like it still is a very pretty looking application it has a lot of features in it that are interactive go over here I can remove this and it sort of swipes away so there's a little bit of JavaScript I think maybe even jQuery sort of plugged into here to give it some interactivity but it is just a pure rich Rails application whereas you know this other example was an application that I built which has vgs based components in it i was building this along with the class but i didn't actually finish this product because there was just so much more work i have done a version of the product project on my own which was based on rails and rails is just such a rapid prototyping and building framework that you can just get things done so quickly and I just felt like when I brought in JavaScript and when I brought in react especially because I was new to them there was a lot more to do and a lot more to learn so yeah that's just a little bit of some guidelines or some maybe even some caution around potentially using react in your application I don't I won't stop you from doing it but as I said if you don't have previous experience in it you might want to just try going the rails only route and I think that's all I got for you for today I have one question here so could you go back to the app JSON without material I I'm looking I'm just checking for add JSON on the other branch yes yes yes so I will definitely do that so that is this right here the add JSON that's right here so there's there's the ad JSON I will take all of this code and I will put it up it's not currently up on a repository but I will put it up on a repository so when I post the lecture the screencast of this lecture I will also post a link to this repository and I will have one branch that points simply to like this right here where it's the application without any styling and then I will have another branch that is the styled with material UI styling before I let you go for the day does anyone else have any questions really about anything that I covered this week so if we think back to some of the work with rails and api's our addition of cores into rails to allow for the cross-origin requests from JavaScript any of the stuff today that we did with react or the create react app fetching our various endpoints or even that stuff I cover just quickly at the end which was bringing in the material UI components and making use of those any questions from all of you on that and yeah so again I will say in the project if you are thinking about using react reach out to me let me know and if you run into any problems with it along the way also let me know so I can help you get past those so that that's that's you can get started on the project right away those we have someone in the chat right now it's CJ just saying can I get started right away yes you definitely can get started on the project right away in fact I would recommend it because the first round of markings and the first milestone is next week I'm going to actually send out a a list of times when I want to see all of you just to sort of check in and and have you show me really wherever you're at even if you haven't hit the mile stone meeting them hitting those milestones is sort of a good thing to keep you on pace but it's not you know absolutely crucial I did tweak the milestones slightly I made them a little bit easier to hit especially the first one I'd initially set that milestone as 20 marks and I've dialed it back in both the document and in the marking spreadsheet 2:15 from 20 and so just to make it a little bit easier to hit that first milestone so yeah by all means get started on that project right away the versions of the lectures that I'm gonna be doing next week there's already like last term's version of those lectures up and learn so next week I'm going to be lecturing on using session to persist state in rails and I'm also gonna be lecturing on the stripe API for doing credit card processing but you could go ahead and watch those the pre-recorded versions of those lectures in learn immediately and so yeah there's there's that so I think that's it for the day folks unless anyone else has something else to ask of me remember I'm always available on discord well not always but you know often it's on my phone it's on my computer feel free to reach out to me over the weekend if you run into issues I don't always get back immediately on the weekend but I do get back to students on the weekend even if it's just something like you want me to to quickly look over your er D before you get started because I won't be looking at your Birla project proposals or e IDs really until I see you in our first one-on-one next week but if you do want me to take a quick peek and provide some feedback just DM me in discord and I can do that for you alright everybody thank you I hope it's been a good week for you in this course and your other courses still it's a little bit awkward that we're all you know working and learning from home but yeah hopefully it is going well please let me know if there's anything I can do to make this whole process go smoother if there's any suggestions you email me discord me all those things yeah have a great weekend everybody I hope you're all staying safe I hope you're all feeling healthy get outside every once in a while if you can walk around exercise be kind to yourself if you're feeling stressed if you're feeling anxious reach out to some friends and chat with them make sure you're taking care of your mental health and and that you're feeling that you're feeling good right so yeah have a great day have a great weekend I will see you all next week bye-bye closing down the old meeting in 3 2 1
Info
Channel: Kyle Geske
Views: 774
Rating: undefined out of 5
Keywords: React, ReactJs, React.js, JSON, API, React Hooks, Material Design, Material UI
Id: u03GZVNM1RY
Channel Id: undefined
Length: 96min 8sec (5768 seconds)
Published: Sat Mar 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.