How to Fetch Data in React With A Custom useFetch Hook

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys how's it going i'm back here with another video and today i decided to bring this video where i'm going to be going over how to create a custom hook in react which allows you to fetch data from an api um this is extremely useful and i actually don't see a lot of videos about it out there i do have a video where i talk about how to create custom hooks however um i feel like i needed to create a video explaining this specific feature that you can make and add to your project because it is very useful and i feel like a lot of people simply don't know that this is something that you can do and that would be helpful for you and um for that reason i wanted to make this video you may realize that in this video i'm using a camera and i want to use camera more in my videos so for that reason i decided to edit for this one so before we get into the video if you guys could leave a like and subscribe i would massively appreciate it um it would help push my videos to more people and help the channel grow overall so i'll be very grateful if you guys could leave a like and subscribe and yeah that's that's basically it let's get into the tutorial [Music] okay so um the first thing we want to do is we're going to have a react project so you can see over here we have um we opened up our vs code and i actually already have a project kind of set up but it's very very on it's like beginning stages you can see we only have an src folder and a few files inside of it there's absolutely nothing inside of my app component so it's literally from the start i just ran create react tab and i created this project and what i want to do is i want to create i want to use this api over here this api over here is the one that we're going to be using for this project it is a public api so it is free and um basically it's a very simple api all it does is you make an api call it returns um an object containing information about a joke uh primarily we're going to be working with the setup of the joke and the delivery um the jokes are probably very cringy i actually think there are like some offensive jokes here so trigger warning if you if you don't want to see them i'm not going to add them in the video um it's just a public api i don't choose the jokes but basically you can see we have a setup and delivery and that's basically what we're going to be doing we're going to create a hook that whenever you call that hook it will return to you three pieces of information about the api call it will return a boolean which we can call it loading which we can use to determine if the data is currently loading or not and if it's loading we can do something about it then we're also going to return the data that the api call returns and we are also going to return an error variable which will be populated based on if there was any errors during the api call so the reason why we want to do that is because it this kind of pattern is very very common in in any react application um you'll have a component that needs a an api call so you create a use effect it makes the api call and the problem is you create three states one for the data one for the loading and one for the error and the problem with that is because you're creating three states every single time you wanna make an api call like this in a different component so the best way to do this would be to create something like a custom hook or using a library which already does that which i have videos in the past so if you want to check it out however some people like to create their own hooks because it allows them to have more flexibility on what they're using right so you can see over here we have our app and the first thing i want to do is i want to create the the file which is going to continue like contain the hook now you can call this hook whatever you want um i you can call it use query or use fetch those are the two names that i see a lot i'm gonna be using use fetch um because use query for me kind of reminds me of graphql and this is not i'm we're not dealing with rfql here so i'm gonna call it um use fetch and i'm gonna create this component over here uh so a hook is a component in react but the difference is that in a hook you don't return um gsx so you don't return any any visual stuff any ui you only return data and states that you might want to use uh when you make the ap when you call the hook so inside of here we want to make an api call so the way we think about it is we want to make an api call whenever we call this hook so a way to do this is we use a use effect because it will trigger a function inside of it based on the on the fact that this component was just rendered so we use this use effect and inside of here we want to make the api call to our api you can use the normal fetch api that comes with javascript but i want to use axios which i love using it's a library out there that is very useful for many situations so i actually already installed it i just ran yarn add axios but if you're using npm just run npm install axis like this and it should be fine um access is very useful it's very famous as well so um you should probably be using it if you if you have a react app so we're going to import access over here by saying import axios from the library axis and over here what we want to do is we want to make the api call by saying axios.get and passing the url to our api endpoint right which is this one over here but the problem is we want to reuse this use fetch hook many times throughout our application for many different api endpoints so we're not going to directly put the the link for this api over here we're actually going to grab arguments in this component which technically if a component is a function so you can grab arguments like this it doesn't necessarily need to be like props like in a normal direct component so we're going to grab an argument called url which we can pass whenever we want to fetch new data and the url that we pass over here is the url that we're going to pass whenever we call this hook and the good thing is that then after we make the api call we want to we get the data right and we want to deal with the data inside of here so to grab the data we'll just grab the response and inside of here we can grab the data by saying your response.data now if you recall i mentioned that usually you have three states um the the data state the loading state and the error state so we're going to still have those but they're all going to be inside of the hook so that you don't need to recreate them every single time you you want to make any other api calls so let's create those states right now um let's call the use state hook and the first one will be the the data and initially it will be null and the reason why i want to initialize it as null is because we actually don't know uh like not all data will be the same right we might receive data that is an array we might receive data that is an object so i'm just going to initialize it initialize it as no and be fine with it later on we can deal with the case if it actually returns no and the name of the state will be data and the function which alters that state will be set data like this and then we're also going to create the other two states the state that holds if um the data is still loading which we're going to call loading and we're going to call the function set loading and the state which holds any errors that occur during our request and we're going to call that error and set error now loading won't be null because we know that loading will be a boolean so we can just start it out as false and you'll see why so let's think about it this way we have our api request over here and we're making the request when do we want to set loading to true how do we determine when the actual api call is being made and when it's done well this over here is happening in a way so that we wait for this to happen to then um continue forwards right so before we actually make the api request we set a loading to be equal to true and then um inside of here we deal with our data which in our case will be just setting the data equal to response dot data like this so we're actually sending our data to the data we get from the request and then um after this we can actually catch any errors that occur in our api request and this this is already handled by axios we just pass a catch and inside of here what we do with this catch is we just set the error to be equal to the error that we grab from here so we can just do something like this and finally after all of this is done it tried making the request if it succeeded it sets the data to the data that was returned from the api request if there was an error it will be cached inside of here and we will set the error to be equal to the error state but we want to set loading to false regardless of its if it's succeeded or if there was any errors so when you have a promise you can do that by passing the finally case which is just a function that will run um after like completely after no matter what happens um after the promises is resolved and over here we just set um the loading to be equal to false like this and this is all the logic that we really need um the use effect does need a dependency array and the dependency the only dependency that we're going to put here is the url because if the url changes then we want to request the new data right um so that's basically it for having our use effect now we need to return the the three states that we actually created inside of this hook and to do that we can do it in many ways um i like doing it like this i'm going to return an object and the object will contain the data the loading and the error and this is basically it this is actually the whole hook i'm just going to delete it like this and now what we can do is instead of our of any other component in our application we can easily just come over here and just make a call to that hook by calling it use fetch like this um and i do need to import use fetch from um from the our src folder so i'm just gonna say import use fetch from dot slash use fetch and we do need to pass a url to our api so i'm just going to copy this over here and i'm going to paste it inside of here as a as a string and over here we can now destructure the data or the loading boolean or the error now if we don't need those information at any time we can just get one of them we don't need do we don't really need to actually access the loading the error and the data if we just need the data we can just grab the data and that's one of the coolest things about creating your own hook because you don't really need to reuse everything every single time and how do we handle this well we want to make the api call when we refresh the page when we enter into this page so we do need to check to see if the data is loading and what i like to do is i like to put a check over here checking if um loading is true because while loading is true i'm gonna return something so many websites use like a loading spinner or a progress bar i'll just for now put in h1 saying something like loading like this and put three dots to represent that the data is currently loading um then if there was any errors um we can do something like if error uh i just wanna right now just console log the area because i'm not sure like what the format of the error will be like so if there is any errors at least we'll be able to see it in our in our console and finally inside of our application inside of our return statement with our jsx um what i want to do is i just want to have an h1 tag like this and i want to display the joke so what we do is we open and close curly braces like this to represent that we're writing javascript and inside of here i want to access the data so i'll say data and since we don't know if data is going to be null or true what we do is we put a question mark which represents like just just access this information if data is actually not null so we'll basically just show this um if data has been fulfilled so we won't be showing anything if data isn't hasn't arrived yet so we'll just put the question mark here and say data.setup because if you go to the api um endpoint you'll see that we have the setup property which is inside of the object and we also have the delivery so what i want to do is i just want to show the setup then i want to have like a a colon and then show the delivery by saying data question mark dot delivery and if everything is working and if i come over here it actually shows we have the setup for this joke which is why did the koala get rejected and we have the delivery which is because he did not have any qualifications um you see that the jokes are amazing here um but basically at least it's working and it's working perfectly we can just actually reuse this how many times we want we can actually even change the the name of the variable so if we don't want to call this data and we want to call this joke or something like this we can change the name of this by putting a colon over here and saying that this is now called choke and instead of accessing data we access the joke so we're just altering the name of the variable we see that um it still works perfectly it doesn't change anything but we now have a new name for the variable now there's one thing that i want to show you guys um you can actually customize this hub to do a lot more for example you can actually create functions for example this won't work only for um like creating a hook that only works for making an api call when you enter the page you can actually um create functions that trigger the api call so for example i'm going to come over here and down here i'm going to call a function called refetch so like make another api request or just like fetch the data more um and for this it's what's basically gonna happen it's literally the exact same thing but inside of a function and what we do is we just return the refatch as a function over here and now if i want i can come over here and i can just create a button like this say something like refetch and grab the refetch function that we just created over there from our hook which we're now returning and instead of here we can just pass this refetch as the on click and you'll see that and with this we don't really need to refresh our page whenever we want to get another joke or make another api call we can just come to our page and you can see there's this joke over here which coincidentally it's related to programmers but if we want to get another joke we can just click on this and it should show um another joke for us thankfully this joke isn't offensive because trigger warning again i literally have been here trying to record the same segment a thousand times but keep like showing jokes that will definitely get this video demonetized so i don't recommend using this api um unless you want to but yeah that's basically it this is this is the idea you can click on this button how many times you want you don't need to refresh the page and everything is contained inside of this use fetch hook that we created and we can reuse this so many times in our application without having actually to create all the states and just like destructuring them from the return statement from our hook which is really useful now that's basically it i really hope you guys enjoyed this video if you enjoyed it please leave a like down below and comment what you want to see next subscribe because i'm posting three to four times a week hopefully now that i'm actually out of work and i'm waiting for school to start i will start posting a lot more and yeah really hope you guys enjoyed it and i see you guys next time [Music]
Info
Channel: PedroTech
Views: 74,667
Rating: undefined out of 5
Keywords: computer science, crud, css, javascript, learn reactjs, mysql, programming, react tutorial, reactjs, reactjs beginner, reactjs tutorial, react js crash course, react js, node js, express js, pedrotech, traversy media, traversymedia, clever programmer, tech with tim, freecodecamp, deved, pedro tech, axios, react api, how to fetch data from api in react js, custom hook, custom hook tutorial, useFetch, useQuery, react custom hook, react useFetch, react axios tutorial, react hooks tutorial
Id: Vspeudp-M9k
Channel Id: undefined
Length: 16min 36sec (996 seconds)
Published: Mon Aug 23 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.