4 Ways To 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 i decided to bring this video where i'm going to be going over a lot of different ways you can fetch data in react [Music] [Applause] [Music] [Applause] okay guys so i'm gonna go over like i said um all the different ways that you can fetch data in react um if there's a library that i forgot or just another way that i forgot um just let me know in the comments but i'm going to go over all the ones that i feel like are the most common and just explain each one of them so that if you're interested in using this method you'll use it and this will include a lot of stuff like different famous libraries like react query and use swr but also stuff like um the fetch api right which is actually the first one i'm going to be talking about right now so actually just for the fetch api i i already wrote the code over here and i will go over how this is actually works for the other ones i'll write the code as i go but for this one i feel like since it is the most basic way to fetch data in react and javascript in general um i just wanted it to already be written and i'll just go over step by step so as you can see we have an application over here which all it does for now is it just calls this component and this component what it's doing is it is fetching data from this api and this is the api we're going to be using throughout the whole video right all the examples will be doing the exact same thing but the only difference is they will be fetching the data in a different method this first method is the fetch api and we're fetching data from this from this dog api and as you can see over here it just replay plays this api just gives you a random image of a dog and we just display it in our screen right so how does the fetch api works well this is one of the this is the only one actually that works without having to install anything else so the flag api comes from it's built into javascript right all you have to do is when you have a url for an api you want to fetch data from you just write fetch which is a function you put the url to where you want to fetch this data and then what you you'll get back is uh some sort of uh data which is structured in a way that is not the way that we want it to be structured what do i mean by that well when we get data from um some sort of api usually in react and in most front-end applications um you want it to have to be structured as a json right so what we usually do with the fetch api is it returns a promise so we say that after the promise is resolved and we get the data from the api we want to transform the data into json so we always do dot then and put a callback function that transforms the data into json right so what do we do after this well after we get the data as a json uh we we it will be a promise right and we resolve it again by getting the actual data back now this over here just represents the data completely resolved and completely structured that this api returns so all we have to do now is do whatever we want with the data right the data will return um this thing called message and this is just a url to the picture which is exactly what we're doing we just set data which is a state equal to whatever we get from the api and we display the picture right super simple super easy fetch api you can't go wrong with it it is the most simple way to fetch data in in react and you can see it works perfectly but i don't want to spend a lot of time talking about fetch api let's get to the next one which is using axios okay everyone now let's go over the second method which is also a very well known method i use it a lot of times in my videos it is really common and it is by using a library called ax use so you can see we have the same component built in over here but the only difference is we haven't made the request yet when you make a request usually like this it will exist inside of a use effect um unless it is a request that is based on an event like a button click but in our case over here we'll just leave this empty for now and let's start by installing the axios package so to install this package all you have to do is either run npm install axios or if in my case i'm using yarn i can run yarn add axis it will start installing the package and it should go pretty quickly and now that we have it installed all we have to do is we just have to import axios from the axios library then we'll come inside of our use effect which is where we want to make the request and we'll say axis.get like this and over here we'll just put the url to what to our api right so i'm going to put the url to uh the dog api that i got but one thing cool about x is is in order to specify if you're putting a get method or a put method a post method or a delete method whatever http method you want to make you want to use you can just specify over here so we're making a get request i'll just say get but if i was making a post request i could just say dot post right so i'm specifying i want to get request and then i'll just say dot then because this will return a promise but differently from fetch we only need to handle this once because axios will handle and transform it into json um internally so whatever we get from here which is the response is already structured in the way that we want now the response in axiorys if you want to get the data that the api actually returns you have to say rasp.data this will represent the data that the api is returning to your front-end application so if we want to set our our data state to represent this we just have to say set data equal to rasp.data so now all we have to do is we just have to say dot message because this is where we access the url to the picture and now our data state over here is representing the correct information if we come over here you'll see we're seeing a very cute dog and it is completely working so this is another way to actually fetch data in react by using axios it is a very common way and i would recommend you using in some sort of situations now let's go into our next one which is fetching data using use swr so now let's talk about using um some really cool libraries out there and the first one is the swr library so swr it stands for stale while revalidate it's kind of like a strategy and also a library which allows you to fetch data in a very nice way i've used swr a bunch of times in the past i have a tutorial on swr since i a lot of people were asking because it is really interesting and i feel like it will be very popular especially with the new version of react because it is very nice to use when you're trying to use the suspense component that is in in the new version of react so i'm going to show you guys how to implement a simple data fetching logic over here and i will also show you how to use suspense to have a loading screen so in order to use the swr library we have to install it similar to axios i'm going to say yarn add swr and it will start installing it so what we want to do is we want to come over here to the top of our application and i just want to import the use swr hook from swr like you see over here now this hook is really cool it will it it is the basis for making your api request so in this case we won't even need a use effect because everything um from like the data the state to um the use effect is all built in to the library so we don't need to either we don't need to create our own state and we don't even need to create our own use effect it's all built into the library so what we want to do is we want to say const and then we open and close curly braces and we'll say data equals to use swr and then we have to pass two things over here first one is the link to our api which is this over here our url then we have to pass some sort of fetcher which is just a function that will explain how to organize the data when it receives it now it's similar to what we do when we i'm using the fetch api we could use any type of a fetcher over here we could use axios we could use the fetch api which is what we're going to be using but use the swr is just a way to handle the data for you and make it really easy and reliable for you to display that you that data in your ui it's not making the request for you it's just handling everything what's going to make the request for you is the fetch api or whatever api you use to fetch the data so what i want to do is i want to create this function over here at the top i'll call it the fetcher and we'll just set it like this and i would i would recommend you to go over the docks to understand it fully if you're a little bit confused but what we're going to say over here is whenever dispatcher it will grab all the arguments that we pass over here then what it's going to return is basically the result of whatever the fetch api fetches from those args and by the way the args in this case would be the url that we put over here so technically it's grabbing this url and it's fetching the data using the fetch api that i explained in the beginning of the video then it will grab it and just like we did with the fat api it will turn it into json so all we're saying over here is how to fetch the data and how to transform it into json then we'll just pass it over here like this but you might be wondering okay we had to do all of this stuff that we did with the fetch api so why exactly are we using this use swr hook and why do we need this if we are or like we're already using the fetch api again well because here comes the best part of this we didn't have to create a state and we didn't have to create a use effect it's all built in and we can use this data like this but we obviously now it's not returning the it's returned the whole data so i have to say data.message and you can see that if we go over here and we refresh the page it obviously doesn't work now i say obviously because there's one thing we we have to handle and this is important because it is something that it will cause you errors in the future um initially this data might not be loaded completely right it makes an api request and although the the data comes in really fast because fast internet um it might take a little bit right and that small amount of time that is fetching the data this thing is no which means message doesn't exist inside of that object so it's given us an error and that's why it's not displaying the image in this case what we can do is we can put a question mark over here before the dot this is called optional chaining i mentioned it in my previous video so i would recommend you checking it out but basically it just says that if data is not no then try to access the message if it is no then don't do anything so what happens now is it works right it will show the image meaning that the use swr is working now you know something even better than this is the fact that if the data hasn't arrived yet we might want to know what to like show some sort of loading screen in front of the screen right and with use swr it is super easy to do that what we do is we come over here we enable a feature called suspense by setting it equal to true and then in react itself there's something called the suspense component i open over here the app component from this application obviously you can see i've i'm using the same application to access the to do all of this different parts of the tutorial if you want to check out this whole app by the end check out the description the link will be there but basically we have the swr component being called right now right and inside of it we have the use swr now that we enabled suspense what we can do is we can come over here and wrap this around with a component called suspense from react from the new version of react and what happens is if we put a fallback over here and a fallback is just saying that if any error occurs related to data fetching or something like that in the use in whatever component is inside of this suspense component over here then render the following and you can put a loading spinner you can put whatever you want i'm going to put an h1 tag saying that the data is loading so while the data is loading this is what it should display and use swr is really nice because it already has the suspense feature built in so if you want to be able to use the new suspense component if you're using usswr that will be super easy so you can see that now if i come over here and i show this and i refresh the page it will say loading for a bit because it's lo it's that will show while you're loading the data right which is really cool it's a really nice way to handle everything and since it's it's it's defaulting to this over here while the data hasn't arrived yet we don't need this question mark anymore because this will never appear if the data hasn't been received so that means that now if i refresh the page even without the question mark it works perfectly right so this is something really cool another cool thing is now you can also get errors right so you can error handle using this because you can say something like if error over here and this data this error variable comes from use swr they will handle everything for you and you just have to say if error then return a message saying something like uh there was an error or something like that there was an error so if there is an error um this will be displayed in your screen and you can even check to see what error occurred if you want to but yeah that's that's something really cool with the use swr hook so this was basically it for this part um i would recommend using this library a lot i really like it but now let's talk about another super famous library which is called the react query library okay so i left this one to the end because um i felt like a lot of you guys would want me to talk about it and um i really like this library i love it i use it all the time and also because it will prompt a conversation that i wanted to have at the end of the video so what i'm talking about is the react query library so this library is amazing it has a lot of different functionalities but similar to the swr library it's not actually a library for fetching data so you might have noticed that in the swr we didn't actually fetch the data using anything from swr we fetched the data using the fetch api or we could have done with axios or whatever right we could use whatever we wanted whatever way we want to fetch the data but what happened is um what that after the data is fetched swr would handle it right would do something and it would handle the data so with red query it's not that different but the reason why it is so important is because it's usually the issue is not fetching the data it's it's what you do after you get the data back right and with reacquery you can do a lot of stuff with it so one of the things that is most important in my opinion is that react query serves as a really good state management library now i don't mean that you can replace uh redix or or whatever stream management library you currently have in your application by just using react query well in some cases you can but it doesn't mean that you have to because what happens is in any react application there's many different types of states one of the the pieces of information the one of the the types of data that you'll have is the data you get from your api right the data you fetch and that's different from a state that just represents uh for example changes in the ui right those are two different things one depends completely on on an api on on fetching the data on whatever it's going to receive from an external service and one is completely dependent on the user using the application on the ui on what you want the ui to look like so they're very different and for that reason they have different purposes in different ways to being handled so with uh managing your states from data you can do it in a couple different ways for example in this simple example i came up over here where we're trying to fetch the data for the dog in two different components right and our goal is to display the same image twice so similar to if you have a user in an application and you're trying to fetch their age or something like that right um obviously the age will maintain the same so it's the whole idea of whatever i fetch over here i want to do it i want to see it twice in two different parts of my application but i only want to make one request the reason for that is because since it is the same information why would i need to make two requests that's that's you're making an actual network request which is something you don't want not only that but if you do it this way where in each of the components over here you are fetching the data in the use effect like this and um just doing whatever with it the data won't come out the same and you'll see that if i come over here the two images are not the same because we're making two different network requests we can check that by coming over here and opening our network tab on on the dev tools for google chrome and i'll do another refresh and you can see it it actually got called four times and i'll explain why this is just uh because my my application is on strict mode and react 18 so i don't know if i have never mentioned this before uh maybe i'll talk about this in another video but in reac 18 you'll be making a use effect call twice um even though you put just an empty dependency area over here if you want to change that for some reason this isn't this isn't even the point of the video but you could just remove streak mode or use your used effects uh in the way that it should be used so you'll see that um now it's only making two this is completely unrelated but i just wanted to mention that but you can see it's still making two different requests right which is not what we want and for that reason it is getting two different dogs now if we wanted to get the same dog and only make one network request we could do something like this now what we did is we just pulled back the use effect and the fetch call to the parrot component which is this one over here and we're just passing the data that we received back as props to both of the components now since it is only one fetch and the data will be the same and we're just passing it through props um it should be the same dog which as you can see it is so we are only making one network request and we are etching the same dot now this is fine in this use case over here because it is fine sometimes to to drill information or not we're not even drilling over here we're just passing data through props and that's fine that's that's not an issue but um like i mentioned in an example where you have any project where you need to get information about a user who is logged in so you might need the same information many different in many different parts of your application so what would you do in that case well you can't just be passing everything through props and putting everything on the top most level component right so one of the solutions to this would be using react query and this is just a small part of what react query can do with react query what we can do is we can install first the library so i'm going to open this up over here and i'm just going to say yarn add react query like this now there is the npm again just use npm install react query then i want to go to the top level of my components because similar to using something like a context you need to wrap around all the components which you want to take use of the state management functionality of red query um so that all the components inside of that wrapper has access to the different fetches that you make throughout your application so what i'll do is i'll import over here at the top from react query like this react query and i'll import the query client provider this thing over here right and also import the query client so those are two different things so the cl the query client provider um it will just be a wrapper like i mentioned so it would be like any provider using the context api and i'll just put this around all the different components that i want to have access to that i want to provide the data and then i need to pass a client to this now the client will be something we instantiate over here we use the query client library we can just say something like i don't know const client equal to new query client right and then we'll just pass this inside of this and it should be fine now what we can do is we won't be using any states and we won't be using user effects requery will handle all of that for us right so it already takes away that that issue that we have to create our own use effect or we have to create our own state requirement query will do it all for you now let's just ignore this for a bit i'll just comment it out and let's go to one of the components which we want the data like this one over here now there won't be props right we'll be actually fetching the data on each of them but um to fetch data with real query it's super simple i'll just come over here and i'll say import from react query and i'll import the use query hook right this look is really good um it will be used whenever you need to query any information and you'll just say something like this const equals to use query then you you'll put over here two pieces of information the first one it's what is known as a query key and a query key is just a string that will serve as a unique identifier for this request and um its purpose is mainly used for caching so in our case since we're going to make this request we want to see this data twice we need to use the same query key twice so that react query knows that we're trying to get the same information so i'm just going to call something like dog and um if i use this again with the same query key over here react query will know that we're trying to make the same request now like i said we still need to fetch the data so over here is where we put something like this over here right the actual fetching of the data so i can say fetch and we don't need to set the data so i'll just do this and we need to create a function over here which will return this so i'll just say this function returns whatever this fetching returns right so i'll fetch the data turn into json and then return this to react query now i can copy and paste this over here because we're also making the same request one thing i want to point out is i like to actually create functions that represent each request when using reacquery so i would create a file over here saying something like obviously i wouldn't name it fetchers it would it would be placed in a better position but just for the purpose of this video i'll just create this file and put it over here and then i would create a function that would be called for example get dog now this function all it's all it does is it just returns this over here this exact thing over here now i'll just return this actually i won't even open this up i'll just say this it's returning a function that returns this and i know it looks weird but um i just find it to be easier because now instead of having to write this twice or three times or how many times i want to use this i can just say get dog and import this from um the fetchers function so i'll say import from um dot slash i need to go back twice and say fetchers and then just import the get dog function now i can just use this how many times i want and um it's fine it's perfect so now what i want to do is i actually have this two calls for the use query now what do i do with it well where i query will handle everything and it will return a bunch of pieces of information inside of this little object over here you can see exactly what it returns i feel like it should show over here it is in the documentation if you're interested but there's a lot of stuff you can get you can get the data that returns just like we want right so if i save this over here and i put data as well you'll see that it will work if i come over here you'll see it is showing the same dog which is exactly what we wanted um so data search for that um there's also like i said there's this is loading which is similar to um how i mentioned in the swr part of the video you can use it to say something like if is loading then return a little message saying um loading right i'll say something like h1 loading and you'll see that while it's loading for one of them it'll say loading right and there's also the error you can get a lot of stuff you see just for erroring you can get so many pieces of information and it's really nice it's really good um but one but the main thing that i wanted to talk about is the fact that now it is only making one network request if i come to the network tab over here and i search filtering just for this kind of request you'll see it's just making one but it's getting two to two images right it's it's although it's being fetched twice in the sense that i'm calling the use query twice it recognizes that it has the same unique identifier and it will only make the request once now similar to the use swr hook um i mentioned that this over here is something there's something interesting with this because if i were this is only working for one of them right but if i were to put this over here grab the is loading boolean from here as well you'll see it will show twice right and that's that's bad it will show twice because there's it i'm doing it twice right so how do i fix this um similar to the usswr hook um we can actually configure this to to have suspense enabled um which is really cool all the configuration you can do is over here by just saying something like default options and you can pass an object and one of the options is queries which when you're specifying the different options or different configurations that you want for your queries you can specify that suspense is equal to true which similar to the swr library now means that instead of checking this putting a fallback um individually you can just use the new suspense uh like component from uh from react so i'll just import suspense from here and i'll delete this as well and i'll just wrap both of this with the suspense hook or the suspense component and put this like this and then i'll put a fallback over here which is the same loading thing by putting an h1 and saying loading now if i save this you'll see instead of saying two it will only show once which is good it's good for ui development um i really wanted to show this for uh because it is a new feature technically it's only been released for react 18 but um i just wanted to show cause it's really nice and this is basically it for react query obviously there's much more to all of those libraries right there's way more that i could have spent a lot of time talking here but i just wanted to introduce all the different ways that i feel are the most popular i obviously i left a bunch of them out right but i chose to just show those four because those were the most commonly known and also because um i wanted to prompt up the conversation that um a lot of people 95 of people fetch data wrong in react um not just fetching data wrong but also handle the the data they fetched wrong and this is a very common disease in the sense uh in the react community this whole fight between um which library used is is not important because every library suffers from their developers not actually um using react correctly i'm not saying that i follow best practices all the time i'm just saying that if you're obsessed with um trying to make your website as best as you can trying to write the best coding react possible you will end up having a pretty good solution for whatever problem you have in react and with data fetching a lot of people ignore issues like fetching the data twice or making your component re-render unnecessarily or um writing code that doesn't make any sense so in my opinion uh going over and understanding all the different libraries are all the different methods you can use to to do such a such a crucial part of of any web application which is fetching data is really important and i would recommend i only show the four most popular ones because they are the ones that are going to cause the most impact if you if you don't um spend time learning each of them or understanding the different ways i don't feel like you'll have the correct knowledge to choose the method that fits well with you so if you're looking for me to choose which way is the best one which way is the best practice i won't because there's no best practice it you should look at every library as if it is a company you're investing you should look at how many people are maintaining the library you should really look at what the react query team is doing or what the swr team is doing because if you start an application using one of those methods it is really hard for you to transition it will take a lot of time so uh that's something i wanted to say now i'll say that i've used every single method in the that i mentioned in this video and i like all of them obviously some are better than the others but um i really hope you enjoyed this video um if you enjoyed it leave a like down below and comment what you want to see next subscribe because i'm posting twice a week and i would massively appreciate it if you want to help support the channel just let me know in the comments um leave a like if you want to help support the channel uh i have a discord group you want to ask questions there you can go ahead i'm trying to grow my community and i would really appreciate the support so with that in mind i see you guys next time [Music] [Applause] [Music] [Applause] [Music] [Applause] you
Info
Channel: PedroTech
Views: 52,545
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 fetching data from api, react fetching data, react fetching api, react query, useswr, react query tutorial, data fetching react, react hooks, fetch api
Id: SbCedTlJWTs
Channel Id: undefined
Length: 31min 17sec (1877 seconds)
Published: Tue Jun 14 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.