Consume an API in React (useEffect, useState, fetch)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody welcome it is caleb in this video we're going to use react to consume an api this is my first react video i thought i'd switch it up and do some front end development so what this is going to do is it's just going to take some data from an api and display it on a page and this is all going to be a single page application style so there's not going to be any refreshes the page will dynamically change when there's new data so let me show you what the application is actually going to look like so you know what we'll be building so pretty simple design obviously pretty much it'll give us something random to do when we're bored and we have the option to load another it'll do a little loading thing and then give us something else to do that's the simple version we're going to start out with but by the end of this video we'll have a version that'll actually add elements to a list so here's how this version will work you hit load the button becomes disabled it will then load a new value and then re-enable the button you can continue to hit this button as many times as you want to get some new information so the purpose of the app is kind of silly but it goes through a lot of valuable principles with react as well as consuming an api we're using boardapi.com which will give us a random activity so we're going to use this api and it's really nice because you don't have to create an account or use any api key so let's get started i'll assume a very minimal understanding of react we'll go through everything in as much detail as needed so for the complete beginner you're going to need to download node.js and this will give us a valuable tool that we can use in the terminal npx and it's a little tiny so let me zoom in and what this will do is allow us to create an application for react very easily by saying create hyphen react hyphen app so npx create react app and then give it a name such as api this will give you a starter application which you can then go edit once that's done you'll have a new folder so you can say cd api to change into that directory and then mpm start this will open a web browser with that application so here we are this is the default and you can see we're on localhost 3004 yours will most likely be 3000 if you have multiple applications running it'll prompt you if you want to run on a different port i hit yes so we have this api directory now and then the source directory and everything starts inside of index.js which renders this app component here which you can see in app.js and this is going to return the html that's necessary to display this page so what we can do is instead of rendering all this stuff we could just render our own component so i'm going to clear out everything in this return and now we're going to create our own component that we can render anywhere inside of our application so we'll leave this for just a second and what we're going to do is we're going to create a new folder we'll just call it components and inside of components we're going to create a new file you can call it whatever you want but this is an app for getting various activities so i'm just going to call it activities.js so the activities component's job is going to be to grab a new activity for when we're bored so to create this we're going to create a function called activities and this is just going to return some html we'll just start with an h1 and we'll just say something fun and at the bottom of the file here we'll say export default activities like so and what this will do is it will allow us to use this activities file in another file such as app.js so right here we can say return activities and it looks like that automatically imported it so you'll just need to say import activities from and then the path to that file so dot for the current directory and then into the components directory and then activities now it ends in a js but that is not required here so you can leave that off for javascript files so let's take a look back at our page and you can see we get something fun now we're not going to really do css a whole lot in this video there's just one change i wanted to make which is this lack of margin is kind of driving me crazy so we're going to go into index.css and just get rid of margin 0 which makes it look a little prettier but that shows you how you can edit the css as well so i think that's all the files we're going to need at the moment so we'll close that close out of the css and now all we have to do is work inside of this activities component so what i want to do now is create the function to request information from the api and then we'll talk about how to get that to display in the page so we'll just create a function we'll actually define it inside of this other function which is totally okay to do inside of javascript and we'll just call this load activity now for this we're going to be using fetch and you can see some information about fetch here and some boilerplate code basically we're going to pass in the url then we're going to get the json from the response and then we're going to log that data so we'll just take this as an example or if you're just following along you can write it out it's not that much code no big deal and once we do this we'll be able to replace this url with the url to get the activities this is the api endpoint so we'll go back to that which is board api dot com slash api slash activity so we'll copy that and we'll paste that right here all right so we have that function and you can see we get a warning load activity is defined but never used we're going to use something from react to execute this function as soon as the page loads so to do that we're going to say import and inside of curly braces use effect from react so once the page is loaded in the browser we want to then make a request and update that page that's what use effect is for so we will put this probably right here so before this return down here and we will say use effect and inside of the argument list we're going to use an anonymous function which the syntax will look like this and then inside of this code we can just invoke load activity there we go so now let's take a look at our page we go back to our react app and we're going to right click inspect go into the console we now have this object here which is the actual activity and when we refresh it'll load and it'll show that activity this api is fairly slow because it's free i'm assuming so just give it some time but eventually we'll get that activity and every time we do a refresh we'll get a new one so we got the activity to load and pretty much what's going to happen now is someone will visit the page it can say something like loading while it goes gets that information which can take some time and then bring it back it will then update the page so that is what you use use effect for and in react this is known as the effect hook it's an example of a hook which you can do more research on now in our code you could just put all this function code inside of this anonymous function here but we're going to actually reuse this load activity to load more of them and it just seemed cleaner to me to do it this way so how do we actually get this information to show up on the page well instead of console logging data what we can do is we can store this data in state so state is basically the information that we want to work with on our web page and you can actually put a comma after use effect here and say use state so the way this is going to work is you're going to invoke use state and this is going to return two values so we can assign it to two variables like so using square brackets and put the first variable followed by the second variable so this is the thing we want to store so we'll just call it the activity and then that second variable is how we can update the actual activity state so we'll call that set activity and then we'll assign it use state inside of the parentheses here is the default state so we'll just use an empty array now if you've never seen this before this can be really confusing as i mentioned i'm just getting started with react videos so i haven't been doing this very long and when i first learned about this i was like what is going on but once you got it down it's not too bad pretty much we're going to refer to the actual activity using this variable and then if we want to update it we will invoke a function set activity so to see that in action we'll replace this console.log with set activity and inside of parentheses we will put the actual data we want to use so it returned data and on that data object there is an activity property you can see here in the terminal so we will put data dot activity and as i mentioned you can use the activity variable here to refer to whatever is in that state so we could put that inside the h1 and to actually render javascript inside of the h1 we use curly braces here and we'll just put that variable activity we'll go back to our webpage and you can see our activity shows up inside of the h1 we do a refresh it's white for a second but eventually it'll show up learn express.js and do another refresh and just to show you guys these are totally random so just to make sure everybody's on the same page the page loads then this function gets executed which will then load an activity and update the state with that new activity value we then grab that state inside of the h1 which we are returning in the jsx code down here let's just make the experience a little bit better we're going to actually create a button which will say load more and when we want to return multiple things we would just surround it in parentheses and then we'll put everything in one single html tag such as a div so let me take this and put it after the button we don't need that semicolon there and then let's just do some formatting and there we go it looks good so we're returning a div with an h1 and a button so far it looks like this it will say the value now if you watch this you'll notice some auto refreshing which is a mistake on my part you'll actually want to add a separate argument to use effect which is going to be an empty array and this is called a dependency array you can research that but that's going to prevent it from just automatically reloading now when we load another nothing actually happens so what we need to do is we need to make it so that when we click this button it'll actually execute that same function that we have up here to fetch new data so to do this there will be an attribute on button on click and we will set this equal to inside of curly braces the function name load activity let's give it a try load another and it'll refresh it the last thing i want to do is make it say loading while it's loading so we don't just click load another 50 times and cause the application to explode you can see when you do that just kind of freaks out so to keep track of whether or not it's loading we can use state similar to how we did right here so we'll copy this and paste it but instead of activity now it's going to be is loading and same process set is loading and there we go the default value for this it's by default going to be true so we wanted to say is loading first thing now what we can do is we can conditionally return something else if it is loading so we'll say if is loading and then in here we're going to just return uh i don't know paragraph loading so by default it's just going to say loading dot dot and stay that way forever because we don't actually have any code to change it to false so when would we change it to false probably after we get some data back so in this then here what we can do is add another line here so let's just space this out some i'm gonna make a little code block like so and then what we can do is just say set is loading using this function right here and pass in false and then same thing when we click the button so we click load activity we want loading to be set back to true so we can just do that at the very top up here set is loading and set that to true all right let's try it out so it says loading give it a second ah there we go make a new friend load another loading write a short story all right so that's v1 of the application next up i want to actually keep a list of all the values and not replace everything each time so instead of the html switching to loading we're just going to make that button be disabled and add to the html so i think the first thing i want to change is instead of working with a single activity i want to work with multiple activities and the default state here is an empty array which i guess i was forward thinking as originally we wouldn't have needed an array just using a single activity however now that we're going to be working with multiple activities that makes a little bit more sense so we'll switch this to set activities just to be consistent and now we'll just go through and update the words but this set activities is going to replace everything inside of the activity state so how do we actually append to the state to increase the list size instead of replace everything what we can do is we can pass in an array and what is going to go inside of this array so the first thing we want in this array is the original activities so we'll say activities and you can grab each element using three dots at the beginning so this is how you can say put each element from the activities array right here and then we can add another element after a comma which is going to be coming from the actual json so we'll say data.activity there we go i think everything's spelled right so far we just have to go down to our html and instead of printing a single activity we actually need to put multiple activities which can be a little bit more complicated what we're going to do is we're going to create an unordered list and inside of here we're going to create some code to loop through all the elements so to do this we'll just say activities dot map and what this will do is allow us to execute a function for each element inside of activities so we'll just do an anonymous function here and all we're going to do is return a list item to get the actual activity we need a parameter year activity so it'll go through this activities array and each iteration the activity will be in this variable we can access it using the activity variable here so let's take a look do a refresh here it says loading it gives us one element load another and gives us two load another three awesome so far so good it's not perfect we're going to improve it we're also going to fix this error here each child in the list should have a unique key prop so this is a thing with react where to distinguish the different activities we need some unique identifiers so we're going to have basically a key with some value right here now the actual api does have a key for the values so if we go back you can see there's key with some number in a string so to grab this instead of working with the activity value directly we're actually going to work with the activity objects so we'll just do the entire object there and this is going to change our code just a little bit we now need to since this is going to be the entire object this entire thing we need to be a little bit more specific and say we want this attribute so we'll go over and say dot activity and then for the key we can say activity dot key so i think that should work let's go over to our code check it out clear the console and do a refresh to make sure everything's good and there we go we're not getting any errors about the key and our code should work exactly the same way now what i want to do is i want to change it so that instead of showing loading every single time it only shows loading if there are no activities otherwise we could just expand on the list we don't have to replace everything so we can say activities dot length if this is equal to zero then we'll say loading otherwise there's no point in it so let's try this we'll do a refresh it says loading there we go load another and you can see it loads that information without changing the html a whole lot it looks a lot better the only thing now is to disable this button because i can click this like 50 times and it we don't know if it's see it's replacing values we don't want to do this so to do this we can actually condition on if it's loading whether or not we want this button to be disabled so we'll go back to our html and there is an attribute on here disabled which you can get from is loading just like we were doing before to to load the html well now we're just going to do it for the button so if it's loading we want the button to be disabled so let's try that now load another the button goes disabled so i can't click it anymore it just loads one element we do a refresh and it properly says loading at the beginning so there you go that is the application so far so good let's see what you can do with this this is just how to do a get request obviously as you continue your application building you'll need to learn how to send data to a server so this is just the bare basics so i wanted this video to not necessarily be an introduction to react although i hope that was part of it i wanted it to be how to consume an api as simply as possible direct to the point so hopefully this taught you how to do it i think i'm going to look into using redux and some different approaches to making a request to an api that might be a little bit better so stay tuned for some upcoming videos if you want to learn more about full stack web development we also have some python back-end videos and we'll probably be doing some front end consumption of an api in a little bit more detail for my upcoming python backend course it's a back-end course yes but part of that is understanding how to consume the api so look into that as well if that's something you're interested in i have links in the pinned comment to get early access to the notes so you can follow along and you'll be notified through email when the course is actually released if you have any suggestions on how to make this application better or any magical react tricks and tips drop them in the comments section below and stay tuned for upcoming episodes peace out [Music] [Music] you
Info
Channel: Caleb Curry
Views: 21,889
Rating: undefined out of 5
Keywords: react, api, react api fetch, react api project, react api, javascript api tutorial, javascript, javascript tutorial, useeffect, usestate, fetch, javascript fetch, react hooks, react tutorial, reactjs tutorial, useeffect hook, usestate hook
Id: ALdtGsyTh2E
Channel Id: undefined
Length: 21min 6sec (1266 seconds)
Published: Thu Feb 03 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.