React Query - Data Fetching Hooks

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey it's Lee holiday I hope everyone's doing well I'm up here self isolating in Canada and today I wanted to cover a really neat tool called react query along with its counterpart react query dev tools and first of all what is react query it's basically a tool for fetching any asynchronous data so any data that would give you a promise so it doesn't have to be limited to graph QL in fact we're going to be using a restful api today to show it it could be graphical but it doesn't have to be it's anything with a promise anything asynchronous react query is very similar to the SWR library from Zeit if you've used that so that follows the stale while revalidate basically it will serve up and show you the cache data while it's going Andry fetching the latest data but anyways why don't we get started today we'll be looking and using a rates API basically showing currency exchange rates over the world so I've got this this over here you basically pass in show me the latest rates you can pass in a base currency to go off of and then it will return you your response so why don't we get started I have over here a crate react app that is saying nothing but the word app right now and just to give an overview of what we're dealing with create react app I've got only two additional packages installed right now those would be react query and react query dev tools and over here in the app I've got my imports already set up so I don't have to remember that for the video and but I'll just basically go over them quickly I've got react query dev tools that's gonna show me what react queries doing it's a really nice um development tool for that and use query which is a function from react query that we'll use to go and fetch us our data so I've got my app component it is returning the word app right now and I'm actually not going to be working in that right now I'm going to be creating a new function called we'll call it the exchange function and for now we'll just return the word exchange in a div like that and we'll hook it up to our app so what we're going to do is use our exchange and right below this we're going to embed our react query dev tools component so you include that right inside of sort of as high up in your component hierarchy as you can and there's a prop what's it called initial is open initial is open that will set to false here so if I were to go check out our app we should see the word exchange being printed out that's great and in the bottom right hand corner we have this little image here clicking that will show us everything that's going on in react query so we haven't actually used it yet so we're seeing no data but we'll get to that very shortly all right so to get started we are going to set up a variable with wildy structure some data out of it but nothing for now and we'll call the use query function so use query by sort of default wants two values the first being a key so this would be a unique key to sort of differentiate one query from another and then a function whose job is basically to go and fetch the data and return a promise that will eventually resolve when when the data is available so why don't we call this function fetch exchange so it doesn't exist so we need to go create it right so we'll just say Const we can just do normal functions Const sorry function fetch exchange and because it's async why don't I actually do it as Const okay sorry about that so conce fetch exchange and that is equal to an async function and we're gonna do a sync because we're dealing with promises here so that will allow us to use the async await support so in here we can go and use fetch to go and fetch the exchange rate data so we'll say cost response equals a wait for fetch to go and make that HTTP request so I'm just gonna pop over here and get the the URL to call like that for now we'll just lay this like that place this in so response gives us a promise that we can then ask for the json data which is also a promise we get the double promise going on so response Jason like that and then we can return our data so if we come back to the app we're still not showing anything but if we look in here our dev tools we can see that it's going and it's performing our query and what's really cool is that over here on the right we have options to either remove it refetch it we can also see what it's returning back so this is the data it's responding with the base is defaulting to euros along with all the rates of euro into the different currencies date etc and it also shows us all of these sort of config options for this query that was performed so for example config if it's going to retry three times so if it fails the first time it will try another two times we could use this configured with suspense and there's a few other options how long to cache a value for whether to refresh on window focus so what that means is if we sort of go to this window and come back should it automatically go and refetch the latest data so it's pretty cool it allows you to visualize all that's going on we haven't showed any of the data that it's returning yet so let's do that now so it's going to return us a few different well an object that we can grab some some values off of the first one is the status so we'll go from basically loading to I think success and but it might also be an error if it if it doesn't work it's going to give us the data and it's going to give us some information about the error if there is any so why don't we start by checking this so if status is loading why don't we just return a div this is loading data thought if status is an error why don't we return a div this is error and then we can embed the error message that was given back to us so if we get to sort of below these two have statements here we can basically assume that it worked so why don't we inside of this div create a pre and then inside of the pre we are going to stringify the response so I'm not going to worry right now about sort of accessing the data and displaying it nicely and all that we're just going to stringify it so data no replacer function but we'll give a spacing of two so that it looks nice so if I were to come back to the screen now we'll just close this here we can see our response so we have a base currency of euros along with all of the different exchange rates from euro into those and the date and we can come into here and still see this hasn't really changed from from just a second ago but let's see what it would look like now to use dynamic values so basically I want to pass in some data to the fetcher function maybe to fetch us a base of US currency instead so why don't we start off simple and we'll hard-code currency to USD and what we can do now is replace this latest here simply with the currency variable so how do we access the USD currency up inside of this fetch exchange function basically any keys that you pass here also get passed to this function up here so we can nice and easy swap that out for currency and then we can change our query here and we can say we want a base of and we'll just embed that in USD so if we come back to the web we can now see that we're we're dealing with a base of USD and if we popped open our tools we can see that we've performed one query here with USD so that has become our key so the key can be to be a string it can also be an array so if you were gonna be passing maybe like a from an a to currency you can pass those in and those all get passed up as individual arguments to this function as its called or parameters so why don't we turn this into something that the user can control so we'll convert this into state so we'll say Const currency and set currency is equal to use state will default it say to USD now let's go with with my currency Canadian and inside of this div will give some buttons that allow the user to switch from one to the other so button with an on click that calls set currency and sets it to cat so we'll say cads there and we'll just do to it to others so we'll have a USD one and we'll do a euro one as well like that so we come back we can now see we've got CAD USD and Euro why don't we make it a little bit nicer just put this beautiful h1 up here showing currency like that yep that's awesome so we can switch this over to USD and switch it to euro and you can see here it's performing the different queries and it's showing you sort of which ones are inactive now which ones are stale meaning we're serving up cached results which ones are fresh and which ones are currently fetching fresh meaning it's sort of fetching it for the first or it has fetched it for the first time fetching is in in progress and the thing is we're not even really seeing the loading state because this thing's serving up data from cache and it's super fast and no even refreshing I think it shows loading for for just a few milliseconds but that's fine so this is how it's sort of going from one to the other and it's reusing its cache data so that's super fast we can click in here and see what's going on we can tell it to refresh we could remove it so by switching to USD again it will pop back in here so how does an error look like so let's just trip it up let's change it to an API that doesn't exist so what we're going to see here is it looks like it's loading for a long time and it's actually not loading for that long what's happening if we were to go into the oops the network tab and I think the reason it's failing is because let's just ferm here okay I think the reason why is this error isn't a string it's um it's a JSON object of some sort so why don't we just die Jason does string of five year so that we can actually see what's happening so loading you can see that the API is failing so its failed once twice three times and after the third time it will show us that there's an error and it's doing it again now I think that's because on focus its retrying this thing again so let's wait and their air so error contained nothing strangely enough so let's click into here and see what it's what information it's giving us so the state it's retrying again fail your account two more failure count three and then finally it should switch to a status of error and no great information for the air so anyways that's something to look into now cool and the reason it's retrying all the time is because I think it's set to configure refresh on all window focus true so that's why sort of every time I work was clicking into the dev tools that the chrome dev tools and then clicking back into here it was retrying because it viewed that as a window refocus so anyways all of these config options can be passed in I think they can be passed in here so we could swap prefetch all in window to false if we didn't want it to to do that functionality so now I could come in here to config and see that it's set to false we could also switch up how many times it should retry before failing I fit instead of returning an error if it should just throw an error so you had an error boundary setup and you wanted to catch it and handle that differently so there's a bunch of options we can we can set and you can set them sort of either locally on every use query call but there's also a component you can place higher up sort of like a context provider in your app to set these configuration options globally so let's just get this passing again it's working we're switching between currencies and let's just review what we did today so we started up here by importing use query function from react query along with use query dev tools from react query dev tools inside of our apps so sort of higher up on the component hierarchy we imported our exchange function which will show us the exchange rates and this react query dev tools component that is initial is open set to false so if we pop down to exchange we have some a currency that said in state and we're passing that currency to our use query hook along with our fetcher function that will receive the currency and go and fetch this data using the fetch function provided by the browser and we passed in some options as well so that it doesn't refresh on window focus we handled the loading state by showing loading we attempted that we made a poor attempt at handling error State by trying to show the error so we could simply just switch this out to there was an error sorry actually don't need this error anymore but we also handled when it works so if it gets down here it should be good we added some buttons to swap the state out as the user clicks to switch ative different based currencies and then below here we just showed what the current currency is along with the data that was returned from the API so up here in the fetcher function we received all of the keys that were passed in we just passed one key but you could have also done it like this in an array so that works as well and this would allow us to pass multiple keys up that we can receive here in our function and we used fetch here waited for the promise of the response then waited for the response to give us some JSON and then we returned that data so that's it for today we covered react query and its dev tools really cool library with a ton of functionality we didn't cover just for example it handles pagination really well it handles mutations and this isn't mutation in the sense of a graph QL mutation although it could be but it's I believe it's sort of for posting data in any way and we handled so we didn't show this but it can handle cancellation using the abort controller with fetch and it can also handle suspense so give this a try hope you enjoyed the video have a good day bye
Info
Channel: Leigh Halliday
Views: 20,450
Rating: 4.9794869 out of 5
Keywords: react query, react remote data, react data hooks, react hooks, react async hooks, react graphql hooks, react rest hooks, react fetch hooks, react fetch, react promise hooks
Id: OorL3E7oCjA
Channel Id: undefined
Length: 18min 3sec (1083 seconds)
Published: Wed Mar 18 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.