MERN Stack Tutorial #9 - Fetching Data

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right then so we have our base react app up and running but now what i want to do is try and fetch some data using our back end api and i'm going to do that from the home page i want to try and fetch all of the workouts and list them in the home page so to do this we'll be using the use effect hook so let me do this right here use effect i'm going to also import this at the top so come up to the top we want to import use effect and also import the use state hook as well because we'll be using some state in a second and that comes from react okay so we've imported those two things and the use effect hook fires a function and it's going to fire a function when the component is rendered now we only want to fire it once when it first is rendered we don't want to go out and try and fetch it multiple times every time the component is rendered so to specify that we do a comma and then as a second argument to this use effect hook we pass in an empty array this is the dependency array and with it being empty it will only ever fire once when the component first renders so what we want to do now is we want to try and fetch the um the workouts from the api on the back end so what i'm going to do is create now a constant and it's going to be called fetch workouts and it's going to be equal to a function and it's going to be equal to an async function like so so all of the fetch logic is going to live in here now the reason i've done this is because i want to use the async keyword and we shouldn't make this async right here but we can create a function inside it which is async and then all we need to do is call that function so i can set the bottom fetch workouts like so and now we can use the awake keyword inside this function so we'll say const and then response is equal to a weight and we want to use the fetch api so fetch and then the uri is going to be forward slash api forward slash workouts only we also have to add in local host as well so let me paste that in at the front so we have localhost port 4000 which is the backend server forward slash api forward slash workouts right so that's going to fetch the data and store the response in this object right here now so now what i want to do is i want to pass the json from this response object into something we can work with so to do that i can say const.json is equal to a weight response and use a method on it called json and that passes the json and now we should have an array of objects in here workout objects so what we want to do is check if the response is okay first of all and we can do that using an ok property on this thing right here so we'll say if response dot ok then do something and we only want to do this if the response is okay because if there's some kind of error and we don't get the data back then we don't want to do whatever we're doing in here and what we're going to do is update some local states but we need to create that state first of all so to do that we'll say const workouts and set workouts is equal to use state and to begin with the state is going to be null but if the response is okay then basically we want to update the workouts using set workouts and the value of it is going to be this stuff we get back the array of data so we'll say set workouts and then we want to pass in the json and the reason oops the reason it's going to be an array of workouts is because if we take a look in the back end inside the controllers the workout controller where we get all of the workouts you see here we get them all and store them in workouts and we send that back as json so this is an array of documents from the database so when it comes back in json format we pass that and it becomes again an array of objects where each object represents a workout okay so that's all we pretty much need to do inside this use effect it's going to fire this function when the component first renders and then we have after it's run the workout so what we can do is cycle through those workouts now down here so i'm going to get rid of this h2 and then replace that with a div with a class of workouts so we can style it later and then down here we want to cycle through the workouts but we only want to cycle through them when we have some so we can do a little conditional check here we say workouts and then double ampersand and then workouts dot map like so and we fire a function then for each individual workout and return some templates so normal parentheses here not curly braces because we're returning some template and what this does is say look only if we have a value for this then we'll start to map through them if this is null which is to begin with then this is never going to be run this code only when it's updated right here and it has value will we map through the workouts now when we do this we get access to each individual workouts so we can output it now in the template so what i'm going to do is a paragraph tag and it needs a key in react and the key has got to be unique so it could be the workout dot underscore id because each workout has that underscore id property and then inside the paragraph tag i just want to output the title so the workout dot title like so so hopefully this is all going to work now but it's not going to work until we start up the backend server we have the front end running right here but the backend server isn't running so we need to open up an additional terminal cd into the back end first of all and then we want to run npm run dev to spin up the server for the back end and yep okay that's all up and running so now hopefully this will work so if we try and preview this in a browser we'll see that if we open up the console in the developer tools we're going to get an error and this error means that basically we're trying to access the back-end server from a different origin server so in our case we have our back end node server running on port 4000 and then we have our react development server running on port 3000 that serves our react application so we have two different servers one for the front end and one for the back end and we're trying to make a request from one to the other right and by default those cross origin requests from different servers are blocked for security reasons now there's a couple of ways we can get around this while we're developing the application the first option is to install a package called cores which stands for cross-origin resource sharing and use that on our backend server to allow these cross-origin requests the other option which is simpler for us while we're developing the react application is to add a proxy field to the frontend package.json file so then open up your package.json file inside the frontend folder and add a new field called proxy at the top and then we set this equal to the development server address which is localhost port 4000. so this is the address of the node server right and what this property then does is tell our react dev server to proxy any requests that it doesn't recognize to our api server at this address now for this to work we also have to make our requests without explicitly declaring the port number in the request url because now it's up here so now we should just change it to forward slash api forward slash workouts without the local host port 4000 bit and now since react wouldn't recognize this resource internally as a static asset or resourcing the react application it will proxy the request to localhost port 4000 and then forward slash api forward slash workouts and as a byproduct this actually also removes the cross origin request error that we get in the console so this should fix the issue during development however importantly this will only work during development and for production you need to make sure that every request points to the correct endpoints now before you preview this for this to work you need to open up your terminal come to where the react server is running and we need to cancel out of this process because we've changed the package.json file and then we can just run the same script again just to catch that change and then we should be able to preview this in a browser all right so now we can see that workout title in the home page now we only have one document inside the collection at the minute which is why we're only seeing one title there but if we had more we would see more titles and as we go on we will add more as well but now at least we know this is working okay so now what i'd like to do is instead of just outputting the title here for each workout i'd like to create a component which outputs a bit more template for each workout so the title but also the number of reps and also the date and also the load etc so to do that we'll create a new component over here inside the components folder and we'll call this workout details like so dot js and then we're going to import that into the home component so let me do a little comment right here saying components and we want to import and it's going to be work out details and we need to say it's from dot dot forward slash to come out of the home or rather the pages folder then into the components folder forward slash and we want workout details okay so now down here we can output the workout details components for each workout we also need a key prop on this and that's going to be the workout underscore id and we also want to pass in as a prop the actual workout so we'll do that as well workout is equal to the whole workout object so now we have access to that on the props inside this component so now let's go to workout details and create this component so const workout details is equal to a function and then also we can destructure from the props the props that we pass through the workout okay so now inside here we just need to return a template and what i'll do is return a div first of all with a class of workout hyphen details and then inside that we'll do an h4 for the title so we'll output the workout dot title and then after the h4 we'll do a paragraph tag and also a strong tag right here and this is going to be for the load so we'll say load in kilograms like so then a colon and a space and then after the strong tag we can output the workout load so workout dot load and then we'll do something similar down here so i'll copy that but instead of load it's going to be reps and right here this is reps as well and then also when it was created we'll do in a paragraph tag so we'll output workout dot created remember that was the automatic time stamp that mongodb added for us on mongoose okay so now we need to export this export default workouts details like so all right so now that should all work we'll try this out in the browser okay then so looks like it's all working situps is the title there's the load there's the reps and here is the created update looking terrible at the minute we're gonna format that towards the end of the whole project but for now i just want to add a little bit of css to make this look a bit better okay so over to our index.css file and then down here i'm going to paste in a lot of styles again from my repo so you can get that from the link down below remember so we have the home class and we say display as grid and we give this a grid template columns property of three fractions on the left one fraction on the right so we've done this so that the actual workouts sit on the left or the workout details and then on the right later we're going to have a form to add new workouts so that's going to be on the right side but the left side is three times the size as the right size and the grid gap is 100 pixels okay so the workout details div we said give a background of white border radius 4 pixels margin of 20 pixels top and bottom auto left and right padding of 20 pixels position is relative and a box shadow as well just to give it some depth so remember that's each one of the workouts so inside home for each one of the workouts we output the workout details component and that's this div right here that we're styling okay so we're making it look a bit like a card and then we have the h4 inside that margin zero zero 10 pixels on the bottom and then zero left font size 1.2 ms the color of this is the primary variable which is this color right here let's go back down work out details p uh the margin zero font size 0.9 ms color is gray and then finally we have a workout detail span and you know what we've not added that in yet but later this is going to be for a delete button so we're just positioning that absolutely top 20 pixels right 20 pixels cursor pointer background of a kind of like a gray color bit of padding border radius and a color of dark gray so like i said this is going to be for a delete button later on doesn't really do anything just yet but it's there nonetheless okay so let's save that and preview again so there we go my friends looking loads better already and like i said before we only have one because there's only one document in the database at the minute but we will be adding more as we go along and then we'll just have one of these cards for each one in the database so there could be five or six or more later on next up i want to create a form over here to add new workouts
Info
Channel: Net Ninja
Views: 65,370
Rating: undefined out of 5
Keywords: mern, mern tutorial, mern crash course, mern tutorials, react, mongodb, node.js, express, node.js api, express api, express tutorial, node tutorial, node and react, mern vs mevn, full stack tutorial, full stack, full-stack, fullstack, mern stack, mern stack tutorial, mern stack crash course
Id: MEab_a19ZGk
Channel Id: undefined
Length: 14min 7sec (847 seconds)
Published: Fri Jun 24 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.