ReactJS Course [10] - React-Query Tutorial | How to Properly Fetch Data in React

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 this is the episode 10 of my react.js course and on this episode um like I've been telling you guys um since we learned about how to fetch data from an API and we're going to be learning how to use the react query Library this is one of the most important videos so far in the course because um this is going to change completely how we actually deal with fetching data I undoubtedly recommend using um react query for everything related to fetching and react just because it is the best solution out there in my view there are other libraries that are also pretty good but um for the purposes of this course we're going to be using real query because it is what I use whenever I need to fetch data normally now if you want to check out the code for this video it's all going to be in the description this will be more of an introduction to react query because there's a lot of stuff that red query is able to do that will make more sense later so I'm just going to introduce um all of its capabilities um based on what we've learned so far so if you want to leave a like in the video feel free to leave a like down below and comment what you want to see in the next episode I'm really loving this series and yeah that's basically it so let's get into the tutorial [Music] [Applause] [Music] [Applause] okay everyone so as you can see um I'm just going to use the same code that we've been using in the previous two episodes where we just have this like simple web page with three different routes and each of them is represented by a component right and what we're going to be doing is we're going to be using a react query to fetch data from the same API we worked with um in the I think it was on the yeah the first fetching video which is the one that just gives us back a fact about a cat right it's just a public API that requires no keys no signups anything you just go to this URL and every time you make a request to this URL which can be done by either fetching data with your code or by just refreshing the page you'll get a random Json with a random cat effect as you can see over here right um this is just for Simplicity like for Simplicity reasons a very simple API there's only one thing that it returns so that's what we're going to be using right now and I'm going to explain to you guys why would we use react query at all right because I've shown to you guys that whenever I want to fetch data I would just use a use effect and then use either Axis or the fetch API to just request the data and then set that data to a state right if you if you don't know what I'm talking about I would recommend watching my fetching data video it's episode 7. but that's that's what we've learned so far and and that's totally fine right but if you recall um to fetch data with the user fact you actually have to do something that is not recommended you have to come to your um index.js over here and remove the component that is surrounding the app component called strict mode and strict mode already comes with the create react app if you recall the all the setup before episode seven we had this function in the index.js just like this strict mode is something provided by react and it will enforce best practices when you're coding your react application so removing it is kind of bad because we're kind of saying it feels like cheating right and the whole purpose of us removing it was because previously if you see any tutorial before I would say like March 2022 you would see people using the use effect to fetch data but that's actually never recommended and people will just do that including me because it was an easy way to explain to beginners but what the react team did and you can ask my opinion on that I don't think that was the right decision they basically created on the newer version of react um a use effect that is called twice because it tests to see if you are actually following its best practices and that would make requesting in the data bad because you would be requested fetching data twice and that's why we remove the strict mode but they did this because they wanted to tell every developer that you should be using a a fetching solution such as react query so that's the preface to why we want to use react query not only that but react query will facilitate fetching data and and just mutating it and everything related to requesting and sending data to an API um by a lot like it's it's it's it's uncanny how much it it facilitates your life and we'll see all of this as we go but for now all we have to do is start installing the react query Library so in order to install it we have to come over here and open um a new terminal different from the one we are running npm start and um over here we just want to say npm install and then we're going to put this over here at 10 stack slash react query now they changed this before it was just react query so if you try following all tutorials maybe you'll get everything wrong um but but now you have to put a 10 stack um slash red query for it to work now that we have installed it um I want to go to our app component because it has all of the components inside of it right what you want to do is you want to go to the component that is the highest level of where you want to fetch data remember of what what I taught in the previous episode where I taught about the context API the highest level component is basically the component that will that is above all of the other components right so in here the app component contains all of the other components in our app so that this would be the highest level component and you want to set up your react query application at the highest level in which you want to make a request what that means is you can actually put parts of your application using react query and ports every application you're not using react so you got to specify which components you want to have access to react query functionality in our case we're just going to put it on the app one because it is the highest level and we want to have access to react query everywhere in our app right so inside of here I want to import um from the ads 10 stack red query and I want to import what is known as the query client just like this and also what is known as the query client provider now you see the word provider and you you might immediately remember uh what we learned previously about the context provider when you're using the context API and it has a similar um idea to that so I'm gonna I'm gonna explain to you guys in a second in the component that you want to create your react query application you have to create a variable called client and you say const client equals to new query client and this not query just query client and this query client over here it actually allows you to pass on a config object that we're not going to configure right now or even in this video because it's more for a little more advanced stuff but this over here can allow you to do a lot of stuff and this is where you would put that kind of information but the important thing over here is is having the client with us because now we can use the query client provider around the whole app like this and this allows us to specify which components will have access to real query so every component inside of this will have access to real query in our case every component is inside of it because we put all of them in routes include except the navbar which is also inside of the query client provider as you can see and we have to specify that the client for this provider is the one that we created just like this so now that we've done this we have access to acquiring any of these components so let's just go to one of them and test it out I'm going to go to the home component just because it is the home component and we just we can just fetch the data over here like I said before if you if we wanted to fetch Data before we would have to use a use effect and then maybe use ax use or something like that but we don't want to do that anymore now we have access to react query which is amazing right so what I want to do is I want to come over here at the top and I want to import from um adds 10 stack real query and we wouldn't we want to import a hook called the use Query hook now this hook will be used to make requests that you get data from an API there is another one that is used to mutate data to to change data but we're not going to use that in this video we're just going to get data so the use Query is very simple you just come over here and you say const then you put curly braces over here you set this equal to the use Query Hook and the use Query hook takes in two different um pieces of information two arguments to it first of all it takes in an array um and this array includes um a unique key that um this query represents so why do we need something like that well redquery allows us to give a unique ID for each query we make for purposes of later for example caching the data or refetching the data it's just a way to identify all the different queries we have in our application which is really cool I'll show you guys how to refresh data with this later on but it's really important that you put a unique ID over here in our case we're going to fetch data from a cat so I'm just going to put cat as their unique ID and especially because we're not fetching anything else but I would specify this and maybe keep track of all the different um IDs that you have maybe keep them in an object or something like that and just import it and use it in your application then over here the second argument is a function that will actually fetch the data so this is something a lot of people get confused with react query is not a replacement to fetch or axus actually you have to fetch the data and give it to react query so that we add query later on gets the data and handles everything for you so you'll still be having to fetch the data we're still going to import over here at the top ax use from the actors library right we've learned access before it's already installed into this code base but if you don't just install npm install axis we still have to use this because we still have to fetch the data so over here the next argument to it is a function that will do exactly that this function should return what is known as the data from the axis response so technically we could just say something like this we could come over here create the function and say axis dot get just like this and get the actual data from the API uh let's just push the get this thing over here and put it over here this is the link to the API and then saying dot then and just getting the response from the function and just returning back the data so we have to say rest.data over here and give back from this function we have to return the data that the excuse API request gets right now if we just return this right because we are returning that it makes the access request then on this function it Returns the data so when we say return this we are getting this thing over here when it does this um we can actually get this data directly from here and this variable will be like everything that needs to be handled from where acquiry will be handled into this so you don't have to create a state to represent the data anymore this serves as the the the the the state that represents the data you get back from the API so technically I could just come over here and say this is the home page and then I don't know put a P tag and say data dot fact now the reason why we're saying data.fact is because if you recall um it's already showing but you can see you remember that the object we get back from the API includes effect property that has the actual fact right so as you can see now every time we go to the home page it actually shows um the API request but um one thing is if I refresh this page over here you'll see it will break and the reason why it will break is for the same reason I've already explained um fact doesn't exist like data is null until the query is done so there's a couple ways we can actually um handle this we can for example put a question mark over here and what this will do is until data it becomes not null it won't access the facts so it won't try to access fact from a null object because this question mark is basically just saying only X is this if this is not no and this will fix it because that's what it was causing the error right now we'll refresh the data and it will load for a little bit as you can see and then show the actual data for a split second it's showing just the text this is a home page because it is a home page for a few seconds right until the data comes back now this is one of the good things with rare query it's just one of the amazing features it has you can actually get a belief in from this use Query hook called is loading so it already handles this for you this is loading it's a Boolean that if it is true while the data is loading so it is true for that specific amount of time where you fetch the data but the data hasn't really returned yet so technically you can just come over here and say if is loading is true then I want to return some sort of um text saying loading like three dots something like this so instead of returning this while the data is loading it will show this whole thing over here and you'll see that this is exactly what happens it shows loading for a split second um and then shows the actual thing right um on a real website I would put a loading uh like spinner you've seen in many different websites but this is how they actually know if the data is loading or not because of this Boolean um and this is really cool you can actually get also like the error and so many other things that you can get um uh like the time in which an error was updated um is loading error is refetch error is error that there's so much stuff right that is really cool if I get this is error over here I can just say if is error then return a texting um sorry there was an error but the thing is uh obviously we we can't like there's not going to be an error so you guys won't be able to see this but we can actually fake an error by maybe writing the API endpoint wrong and you'll see that it will say the same it will say loading until it fails and then it's going to realize that there was an error right so it's just trying to fetch the data but obviously there's no data to be fetched I can like the same thing happens here if I delete everything um you'll see that it still keeps loading but yeah that's basically it for the most basic features of this um of this library now there's another thing there's the refetch property it's a function that you can get from here which is really cool now imagine a situation where you have your website and you have an API and this API for example um has a list of users right and you're just displaying that list of users and you create a new user so now the data in the back end and is outdated from the data in the front end because the front end won't know that the back end has changed data but you can kind of force to make another request by using this refetch thing over here this is a function that whenever you call it it will request the data again so if I create a button over here and I know this example isn't that good because every time we request the data it will be a different fact about a cat right but there's a lot of situations where you need to update the data in the front end um and that's how you would do something like this so I'm just going to say update data and create a button and given on click over here and all I want to do in this on click is I just want to call the refetch function I can even just put refetch over here and now if I come over here and I click on on this button it will refetch the data as you can see it's updating as we go and remember there's no States in this application so we don't have to update the state everything is handled directly from this data object over here um what is other stuff that you guys might be interested in well um I think people complain a lot that you have to call this data when imagine you have you're fetching two uh two queries from the same component would you have two variables called Data probably not right so this is more of a JavaScript thing but you can change the name of this um to a variable you want so if I wanted to call this cat um effect I can just say our cat's data I can just say something like this can't data and I'm basically replacing the name of this data object or this data property um for cat data so instead of saying data over here I'll just say cat data and it would still work as you can see it's still working perfectly um it's just a small thing that I thought would be cool to see now there's a cool thing that I feel like um is also really interesting and it's the only thing I'm going to show you guys from configuration for react query because I just want to explain to you guys how powerful this is by showing you this small thing that you probably don't even think about but it's important to recognize when you're building a real project for example look what happens when I move to another page I'm going to go to this tab over here and I'm going to come back and you see it will request the data again and that's crazy right but is it really crazy because if you have an application that has a lot of data constantly updating this could be a cool way for you to constantly have your data being updated um even when you switch tabs right usually you switch tabs whenever you stop using the website so maybe you'll spend like 10 minutes on this cat fact website and when you come back you want to have the most updated data so react query does this by default where if you switch tabs or you're not focused on this window um it will just refetch the data you can actually specify if you want that or not by coming to your app.js um over here and going back to the query client that we created I mentioned in the beginning that um you can put configurations here and I wasn't going to show it but I'll just show it real quick because um I think it's cool to show it to you guys so you can put an object over here and you can access a prop uh an object called default options and this over here allows you to put some interesting configurations you can specify which kind of configurations you want to add so you can add a query configuration and a mutation configuration now I know I didn't talk about mutations but um it's a really important topic and concept in um in front-end development and back-end development as a whole just always think about it as a query as being getting a data like making a request for a data so it's what we've been doing so far we we did a get request um to get the data from an API and a mutation would be any kind of API request where you change the data or you create a data you update the data or you delete the way I like to teach is saying that a query is just the the read from crud and mutation is the cud from code right the create update and delete while the query is just the read right so in this case we want to specify we want to change the query and what we want to specify about the queries is we want to say that whenever um there is a Windows Focus we don't want to refetch it so there's this thing called refetch on window Focus we can just set it to be false and whenever we refetch it it will now be like whenever we switch for Windows it will now be false so I'm going to come over here you'll see that we have I'm going to update just so you guys see I'm going to refresh we have this thing over here um a cat has only the ability to move their jaw up and down not side to side like a human can cool I didn't know that but now if I switch tabs and come back it's still the same thing right it doesn't update while if I set that to True like it was by default um it would obviously do that like I will come over here and oh I need to refresh the page but yeah it will now switch whenever I move Pages see so this is just one of the thousands configurations you can actually put um oh this is actually a massive one but yeah um other thousand configurations you can put in react query and this is what we're going to be using throughout the rest of the series until we get to something that doesn't require fetching data but you understand that um this is what we're going to be using and I hope I made it clear how amazing react query is because um this is the whole reason where why why we're not we're migrating from using a use effect and why from now on we're gonna have this strict mode enabled in our react application to m-force best practices in our apps so this is basically it for this video remember all the code will be in the description if you want to check it out just go ahead I really hope you 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 going to be posting twice a week this course is going amazing I know the views aren't that high but I I knew this was going to happen um that's why at the end of the course I'm gonna post the same course again inside of one single video because there's people who like this kind of videos and which like this kind of course is where it's all separated but there's also people who love um just a single very long video so I'm gonna do both and I hope that works out um it has got to motivating when I see um like less and less views every time I post a video but trust me I know a lot of you guys are commenting please don't stop the course I'm not gonna stop the course I if I didn't stop my YouTube channel when I was getting 50 views of video I'm not gonna stop uh this course right now so don't worry about it I'm gonna finish this course because I knew this was gonna happen and I'm motivated I really like making these videos for you guys so um yeah that's basically it I really hope you guys enjoyed it and I see you guys next time [Music] [Applause] [Music] [Applause] [Music] thank you [Music]
Info
Channel: PedroTech
Views: 55,142
Rating: undefined out of 5
Keywords: computer science, crud, css, databases, javascript, learn reactjs, mysql, nodejs, programming, react tutorial, reactjs, reactjs beginner, reactjs tutorial, typescript, react js crash course, react js, node js, express js, pedrotech, traversy media, traversymedia, clever programmer, tech with tim, freecodecamp, deved, pedro tech, react query, react-query, fetch data react, react api, useQuery, react query tutorial, fetching data best practices
Id: SYXvHXOJzwc
Channel Id: undefined
Length: 22min 19sec (1339 seconds)
Published: Tue Aug 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.