React JS: How To Get Data From An API With Hooks and Axios

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
yo youtube how's it going i wanted to make a quick video on how to make api requests in a react application this is something that i feel like a lot of beginners uh kind of get confused about um so let's jump right into it first of all i think there's a couple of things that you ideally should already know uh you know you should have react fundamentals right you can't even do this if you don't you know react you should have a good understanding of promises you know so anything that you do in your application that makes a request to something external that doesn't respond immediately right that always returns a promise most of the time so api requests if you're making calls to a database or something like that all of those will revolve around handling promises so you need to have a good grasp of promises i won't cover that in this video but there's a ton of resources about it um let's see uh it's very useful to know and understand hooks in react which is a it's a fairly new concept but it's been around long enough that you know if you're doing any kind of react development i suggest you definitely take the time to learn to understand hooks so the the two main ones that i'll probably use in this video is the use date hook and the use effect hook so i'll i'll use that in my examples today so make sure you have a decent understanding of how that works and then the only other thing you really should know about is you you have to have a way to make http requests so the the two main ways that i've i've seen used a lot is either the fetch api or this library called axios i personally re uh recommend axios over fetch um just purely based on the api and kind of the ease of use i find it a lot more straightforward um the comparison of the two honestly i could probably do an entire video on but um for now we'll use axiorys um so let's get started alright so i have a basic react application here you know i just used create react app to initialize it um it's already set up to you know every time i change the code it should automatically refresh so you'll see here on the right side on the changes are there so first let's talk about how to even [Music] do these api requests the http requests so i mentioned um that we'll be using axios as our http client so i'm going to go ahead and install that the documentation tells me to do npm install axios let's get install it put it in my dependencies while that's loading up there is actually this other tool that we're going to use called json placeholder which allows me to effectively have like a mock server that we can make http requests to so for example you'll see that they have a slash posts here that will return 100 posts so if i do if i click into that jsonplaceholder blah blah blah posts um you know it'll give me this json response so this this part of it uh you don't necessarily need to fully understand what's happening um if you're a back-end developer you probably already do but you know basically we've got this server that if you make an http get to slash posts you'll get this back so what we're going to learn here in a second is how do we make that how do we make our react application perform that same http get slash posts all right so axios finished installing i should now be able to import it like this import axios from axios and then to use that so earlier i mentioned about the use effect hook so we're going to import use effect up here do a little bit formatting so ideally you already know how to use the use effect hook bucket um here's a little intro you open it up like this with parentheses and then within that parenthesis you pass an arrow function like this and then it also takes in a second parameter that we're going to provide an empty array for now what does that mean this effectively just means that whatever is in this code in this block it will run on mount okay so the very first time your your app this component app mounts whatever is in here will run so for example if i did console.log i am here if we go back to our application and view our console logs so every time i hit refresh here the application kind of re-initializes and this component mounts and then it prints i am here so that's a good place to make http calls it's like so usually you might have a component that let's say you have a component that loads these posts right like maybe you have like a a a blog and perhaps you want to load all of your posts when application first loads or when that component that specific component first mounts on the screen so to make this a little bit more specific so how do we make that http call that we just talked about so we can do axios.get and then i'm gonna provide it with a url of this guy which we just showed earlier placeholder slash posts and then what i expect from this is that it's gonna go make that http get request and then it's gonna come back as a promise so i should be able to do dot then and then it's gonna come back with a response and inside that response is let me wind in this up a bit is the data the data that you see on the right hand side of the screen here so if i do console.log response.data i expect to see these objects that i see in an array so let's take a look at what we have here so as you can see when i refresh on the side you know it makes that http get and then we get back this array of objects so that's kind of like the basics of it um not really much more to it now there's a couple of things that we can improve here um first of all how do you usually when you when you get data right from an api you want to put that data somewhere like either in in state or you probably want to show it on the screen so how do you do that that's where the use date hook comes into play uh if you haven't used this before you definitely should check out the documentation but i'll show you some of the the basics here so you can import it like this use state and then first you have to initialize kind of a variable for that holds our data so the syntax is a little bit weird if you've never seen it before but it's it's actually just javascript syntax with the structuring so for example let's do posts set posts this will make sense in a second here use state and then whatever you pass in here is your initial data so we're gonna have an empty array here because we initially want to have um this empty and then when the data comes back to us we're gonna do set posts response that data and then what's going to happen is um this data will be assigned to what this variable is pointing to so to kind of prove that out let's let's go ahead and print it so we'll do posts dot map and then what we're gonna do is for each post we're just going to return a div that um let me take a look again what this data looks like so each object that comes back will have an id a title and a body so we'll do how about we show the title so post dot title so what i expect to happen here assuming i didn't make any mistake is that when app loads it's going to make this http get call it's going to get back posts and then it's going to assign that data to this component state that we also call posts and then down here this should load up as a list of title which i misspelled let me correct that so let's take a look at what our app currently looks like so now we have a list of these titles you know none of these make sense because they don't make sense either here um but that's that's kind of the basics of it now you have um you now have a way to make http calls and then uh take that data and then you save it in state and then you're presented to the user right so very simple there's not much to it but there's a couple of things here that we can improve a little bit so first of all uh to clean this up a little bit let me extract this to a variable all right and then so what what can we improve here um first of all this responds very quickly and in in a more realistic scenario you know it you know you might have a server that takes a little bit of time to to load up so one thing that might be useful there is you know for you to present a loading state so perhaps while it's making a call and it's still kind of pending it'll show a loading spinner or a message and then once it comes back it removes that loading spinner and presents the data so how do you do something like that well then it's pretty simple you just need another state object so let's say that we have something called is loading and then we also need a setter set is loading equals use state so we provide here the initial state which would be false because initially it's not loading and then what we're going to do here is we're going to say on mount is loading should be true set is loading to true now what does that do perhaps let's say that we want to show this spinning react logo while it's loading so imagine that [Music] it'll show this logo while it's loading and then when it's when it's done loading it'll show this list so how do we do that well simply we just need to kind of add a little bit of uh conditional logic here so if is loading um is loading show me my spinning logo otherwise give me my list of posts let me format this so you can see better right so uh the way the syntax works is it kind of works like an if else statement so it's saying if it's loading is a truthy value it will show this else it will show that so the way we have it here because we have it initially to set its loading to true it'll show just our spinning react logo until it's download until we mark it that it's downloading and at what point is it downloading right it's when we're done setting the data when we actually get the data back so this is where we would kind of turn off that flag set is loading false okay so you'll notice in application uh it'll probably be hard to pick but every time i refresh it should show the the loading spinner and then eventually when it's done it'll show the list of data itself now right now uh you're not able to see it because the the browser is caching the request um you know but just trust that that's how it works now that's great um what else can we do here there's also there's a thing about you know anything that is a is a promise or especially with http requests is that it's not guaranteed to always succeed right there's a there's a possibility that it fails like maybe the user loses internet connection or maybe on the server side some kind of problem happen you know maybe a problem with their database or something like that so anything can happen and how uh how that usually works is a server would respond a different http status code to kind of say you know that hey something went wrong so that's usually status codes that are in the 400 to 500 range so ideally you need to make sure that you're catching those potential errors so how do you do that with with axios now if you understand promises well you should know that there's also a concept of promise rejection and now with axios what it will do is if the http request failed it will actually turn into a rejected promise so you can add a catch block here um and for now we'll just do um console.log there or just log out the error for now okay so we don't see anything different here obviously because our mock server here will always almost always respond successfully there's this other tool that we can use that is great for simulating different http status codes so for example let's pick a status 500 here internal server error so if we take this url http stat that us 500 it's going to give us basically like a simulated http request that responds with a 500 status code so if i provide that as my url over here and i'll just comment this out because i'll use that later we know that it's now going to make a request to that and it should fail so it'll go down here and so how do we expect that to respond on the ui at the current state we should just see that it's it's kind of stuck on a loading state right because it never gets to uh the resolution over here and we should expect that it logged out an error you know request filled with status 500 now that's great but it's still not complete you know ideally you you kind of let the user know right that your application failed somehow so how do you do that um you know maybe you want to present a message of if something happened something wrong happened present in an error message so how do you do that kind of same idea right as you introduce another variable let's call it error provide a setter and we'll initialize this to nothing because you know initially we don't want an error and then we'll add a little bit of logic here of perhaps um if error so if there is an error uh let's just say sorry something went wrong obviously in a real application you know you'll probably have a better graphic or a different message here depending on your use case so alright so the missing piece here is now that we have a new error state and that we have some logic here of if there's an error you present a message so we're going to replace this log with set error right so this is the error that comes back if it failed to make a request and then if that happens we'll capture it and if we're able to capture it we'll present a message so you should be able to see that on a browser all right so now we're able to capture our error states and we're able to inform the user when an error happens with the http request i'm actually going to refactor this a little bit to make it a little bit more cleaner so what i'm going to do is i'm going to pull out this loading state up here and then we'll just do uh if it's loading kind of same thing return me my spinning logo and then over here we'll just remove that conditional so what you should see is now let me put this back to the working http request what you should see happen is when you when you load the application just to review it when you load the application it's gonna make our http get to get the post back and then when it comes back to us we're gonna capture it save it in state and then we're gonna tell the app hey stop stop showing me the loading spinner um so it will only go down here to this final return statement if a it didn't error out and b it finished loading right so it only finishes loading when we get the data back so if we go to the browser you know we should just see our list of posts so that's the that's the basic structure really of making api requests there's a couple things that you can improve uh for example you know maybe you want to move this logic to a a separate function in a different file you know i would i would recommend that and then um or at least this part of it the axiorys.get you might want to move to a separate file just for organization um and then you know you can also turn this into a async and await syntax if you want to so you can do something like async function get posts and this will allow you to kind of clean up your promise syntax a little bit um if you're not familiar with this syntax i also highly recommend um learning about it i won't dive into it too much but basically um let me type this out it's the same exact logic as what's happening here of make my get and then when it's done do this stuff and if it errors out capture it so how do you represent that in a async in a weight syntax so you would do a whoops try catch block right within the try is where you make your actual call i and the nice thing with async it await is it kind of looks like synchronous code even though it's async um so in this line i can do set posts i mean i should actually call this response set posts response.data and then in the catch here we're going to do the same exact thing as this um and of course our loading state um you can move this in here as well just to be consistent so this is this async function here is equivalent to this promise syntax that we have here and it's a little bit cleaner in my opinion um and then only catches you got to make sure to actually call it so that's how you do async in a way inside a used effect it can be a little bit weird because some people might assume that oh can't you just put async up here um you can't actually because uh the use effect is expecting a non-async function to be passed in there so you don't have a choice but to define this get posts inside here if you're trying to do a second weight within the us effect all right and then so that's effectively the same as what we had before works exactly the same and that's it that's kind of the main uh bare bones how do you make http requests in our react application now there is this other library that i would recommend so you know imagine that you do let's say you have a a blog application right you're gonna make a lot of http requests you're going to get posts you're going to load up comments i'm going to load up you know probably authors stuff like that so there's a lot of this kind of boilerplate that you probably don't want to deal with right you don't want to have to keep track of error and loading states for every single one of those so this library that i would recommend you call uh check out it's called react async and let me let me just install it and i'll see you i'll show you how it works so npm install react async let me just copy this so now with react async installed let me pull that in and you will will refactor the code that we have and you'll see how much it kind of saves so import um use async from react async and notice that this starts with use which means it's a hook so i can use it like so use async and then this um takes in an options object that allows you to configure what what it will do so the one thing you you the one you probably care about is promise function this is where you pass in um basically this call and then i actually want to make sure that we just get the data back so you'll notice that the data is always inside response so i'm just going to put that in here okay what this returns what this use asic returns is all the things that we pretty much care about so returns data it returns uh it's actually called is pending and error now each of these is pretty much what we just did here but it's kind of hidden from you it's done internally so i don't need this anymore i can just rename data here to posts and that will be equivalent i don't need this anymore you know we can use is pending instead so i'll replace that down here and then i don't need this guy anymore either because that's what this is you know so just imagine that use async is doing all of that for you behind the scenes and then this entire use effect goes away because what this will do is effectively the same exact thing where on mount it's gonna call this promise function and then when it resolves it attaches that resolved data to data when it's loading its pending becomes true and when it fails this error object gets filled in so that whole thing that we just wrote is eliminated down to three lines of formatted code right all right so that's kind of the basic fundamentals of it right so usually with api requests you know i would recommend that you're somehow maintaining loading and error states and that you're informing the user for each of those things and again react async is a is a great kind of library for doing basic stuff like that like making gets of course with http requests you can also do like puts and posts for creating or updating data not going to cover that here but a lot of it is kind of the same [Music] fundamentals right that you have to manage state as you know whether while it's pending or it comes back or it errors out you have to do something about it and a lot of these libraries really help out in kind of reducing boilerplate so react async i think is a very good library for beginners for those of you that are more intermediate i would highly recommend checking out react query which has quite a bit more features it can do the same exact thing that that react async can do but it has other stuff for so for example like caching it has some uh the ability to retry and refresh automatically and stuff like that so definitely check that one out um this entire library honestly could be its own full video so i won't go into it but it's a lot of the same idea is that if you look at the quick start you know it gives you the ability to make a request and then within the query it has all of those stuff maintained for you like loading and error states [Music] do you
Info
Channel: Marius Espejo
Views: 430
Rating: 5 out of 5
Keywords: react tutorial, learn react, react course, reactjs, react.js, react, react js tutorial, reactJS, axios, react hooks, hooks, useEffect, useState, javascript, es6, react query, react-query, react-async, react async, react useeffect, react usestate, request, http, api, api request, rest, restful, react request, reactjs api request, react http, reactjs http api request
Id: _5Ro8MVMGuQ
Channel Id: undefined
Length: 32min 32sec (1952 seconds)
Published: Sun Oct 18 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.