React Data Fetching with Hooks using SWR

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey how's it going it's Lee Halladay and what we'll be doing today is covering a cool package called SWR from the folks at site the same ones that make the next js' framework and same with the esight now serverless hosting platform so SWR is a little package that basically gives you hooks for remote data fetching as their subtitle implies but it's based off of this RFC whatever five eight six one which is state while revalidate and what that means is it will show you the cached version of your data if it has it and then in the background we'll go and fetch the new version and it will replace that once it gets it and it has a lot of nice built-in things like support for suspense it also has this cool little feature where if you sort of you click off on another tab and you come back it detects when you come back and it can refresh the data it also has some polling so you can get it to refresh sort of every five ten seconds or whatever so this is what we'll be covering today anytime you're working with data you need an API to pull it from and we'll be using this cool little API from the UK police that returns you an array of crimes based on a latitude and longitude so what the data looks like each crime has a category of anti-social behavior drugs or whatever has a location of where it took place and you can query this based on the location and a month so you can get all the crimes near location in in October for example so we've got this create react app which is doing nothing but rendering some text this is SWR right now so if I go over to this let me clear this out again there we go so I've only installed one single package called SWR and we'll be using a hook that it provides and a little bit later this way to sort of globally configure how it works so if we get started we'll say Const data comma error equals use SWR so the first thing you pass to this hook it says a key or a key interface and that's because it it's a very flexible library you could be passing it a path or a URL you could be passing at a graph QL query an object sort of it's up to you sort of how it's implemented but what will be passing is the URL to pull down this crime data so we'll paste that in here and maybe to clean this up we'll put this into a into a variable so the URL like that cool and the next thing you need to pass it is a fetcher so if we come back to the API and we go down to their example you see her fetch and it says fetch function fetches a function which is any asynchronous function which returns data so it's a little bit vague right and this tripped me up a little bit because I thought fetch was just the the fetch the the tool that comes sort of in the browser now for you to fetch get request post request data etc and it was returning me some weird stuff actually I'll let you see what it's doing so if we look at console data we can actually look at the air too just in case there is one so we go into the console so it starts off undefined undefined basically there's no data yet but it's also not an error it's sort of loading and then we get back a response and I was unsure sort of I was trying to access the body and that was giving me this readable stream and I wasn't quite sure what to do with that and I sort of knew what the issue was the issue was that you gotta do that weird double promise thing where you first get a response and then you get the JSON from that response so that's what was tripping me up so what we can end up doing is we can create a function called fetcher and what fetcher was is it it will basically take any args sort of whatever it gets passed and it will pass those args to the actual fetch and then when we have a response we can take that response and we can get its JSON believe that's how it works so now instead of passing actual fetch there let's pass our fetcher function and now let's see what's showing up in this console log so you can see that it's already better what we've got is well first thing you'll notice is it's actually rendering twice and that's because the first time it's rendering is the stale data and now it's revalidating it's going to fetch the new one so then it gets the new data and it rear Enders and that's why it's a rendering twice because of the cache data but now we have actual data we have all of those different those different crimes that are taking place near wherever this latitude and longitude is I know somewhere in the UK and this is for October cool so already we basically have the minimum the minimum example working but let's make it a little bit better we can say if an error we could do return a div that says error if not data what we can do is we can return loading and so if we get to here we've basically guaranteed that we don't have an error and we do have data so we can now deal with this data and instead of just rendering SWR why don't we swap this out for a pre tag and we will stringify the JSON response so we'll do data null because we don't want to replace her and I'll do spacing of two so it looks a bit nicer so if we come back now we're seeing the actual data so we can see this antisocial behavior if I do a load you can see it's loading for a sec and then when it has the data it renders it here so the next thing I'm going to be doing is it has a little bit to do with the SWR package but it's something I like to do and that's basically to split up the fetching of the data from the displaying of that data and I'm gonna build a little thing that allows us to filter the data down by the type of crime that was committed so what we'll do is we'll define a functional component here so function we'll just call it crimes and will basically take most of this stuff for now and we'll put it in here so we really haven't accomplished anything yet but now we have this app and what I'm going to be doing is if you're using this use SWR hook a bunch and you don't want to always have to pass your fetcher your different options and stuff like that the first thing you can do is you can use this SWR config it's a provider and we can wrap sort of the rest of our app around this to set some sort of global settings for SWR config so what we'll do here is we will say SW our config and inside of this we will embed our crimes so what we can do now is we can provide a value to this config and what will be just providing is the fetcher so now I no longer need to provide all the options every time I use the hook it will basically because it exists inside of this provider it will use those global values so it's still sort of working as expecting so we can keep going in our refactoring of this code so what I want to do now is I want to break out the displaying of this data which is just a pre tag it's not much but from the actual fetching of that so I'm going to create a function called display crimes and it will receive an array of crimes for now and we can basically take this and remove it down here so we're no longer working with data we're working with crimes and we'll need to return that from this function here so display crimes to self-closing component and we need to pass down some crimes to it which is just our data cool it's still working so let's keep going in the refactoring and now what I'm going to do is build a way to filter out all of the different categories of crimes so I'm actually going to pass these categories down and how do I get them I've got sort of each category here antisocial behavior antisocial behavior same thing same thing what I want is a unique list or a set of all the unique values so we can do that it's a little bit of a trick but so we want to pass down an array and we want unique values though so what we can do is we can take the values from a set that we produce so a set is just a unique it's a different object type or data type but it's it's like an array but all the values are unique in it so to get all of the Niek unique values what we can do is say data and we'll map the data so each of these is a crime and what we want is the crime dot category okay so if we work backwards we're taking all of the crimes and we're basically getting an array of all their categories we're passing that array to a set which will give us the unique values and then we're using the triple dot which will break out this set back into an array which we're passing down as categories so now that we have categories we can start to do something with it so why don't we just we'll just wrap this around with uh the fragment tag and we can show a list of all the categories right here so what we'll do is we will map the categories and each one is a category and what we want for each of these is a button so we always need to provide a key which will be the category and the value of this button will also be the category like that cool so you can see I've got a unique list of all the the categories here antisocial behavior bicycle theft burglary etc but we're not really doing anything with it right so that's the next step what we're going to do is we're going to get some state and we're gonna have a state property called the filter category so set filter category and we do react use state and we'll start it off as a null value it's not being filtered at all so what we want to do now is when somebody clicks on a button so on click we want to set the filter category and it will be set to whatever category were currently mapping over cool so map the categories create a button for each one on click we'll set that category to be the one that's currently filtered and what we'll do is we'll give it a way to reset so if there is a filter category and we will display a button that says reset and when you click the reset button what we'll do is we will set filter category back to know cool so once I set one you can see the reset shows up disappears but we have and actually filtered any of the data yet so that's the last thing we need to do so why don't we just create a new variable called filtered crimes and let's do a quick check first we only really need to filter when this has a value so we can use a ternary here to say if there's a filter category what I want to do is take the crimes and was it filter or so yeah filter so we're gonna take each crime and we're gonna see if its category is equal to the one currently being filtered like that and if there isn't a filter category well we can just pass on the crimes which is the unfiltered list of all the crimes so now that we have this data up here what we need to do is instead of we're just stratifying for now but instead of string a fiying that we would stringify the filtered crimes rather than the the superset of all the data so if we come back here we start off with all the data we can filter down to bicycle theft criminal damage drugs other theft etc and you can eat this data sort of cool unable to prosecute suspect under investigation it gives you sort of the status of each of these crimes which is sort of cool in another video what I'll be doing is mapping all of these out that's actually why I chose this data set because it has a latitude and a longitude for each one so you can plot them on a map so stay tuned for that coming up and we're basically done this example I wanted to make one further change though so I'm searching data back in October I doubt the crimes that happened two months ago are changing very often because it's the past right but one thing that this package does is if we're sort of browsing over here and we come back which come back it will reach the data again and that may be something you want if your data is sort of changing see every time I come back it's it's a refresh its reef etching the data if it's over um what is it I don't know some sort of timeout that it has but for this data we don't really want it to refresh every time I'm fine showing the sort of older version of that so there's an option that we can pass and that is revalidate on focus so that's when the browser tab gets focused see new new fetch right here I don't want that on here because my data is not changing it's pretty cool though but we can come back and because we're using this global config what we can actually just do is set revalidate on focus false so that every time you sort of come back you can see it's no longer reaching all of the data so there's a few other options we haven't really played around with whether to use suspense or not that might be a cool another video what fetcher we did use that if you want some initial data to be passed I don't think you would use that globally cuz it says here this is per Huck but anyways take a look at all the different um config options you can pass to the hook or to the global SW our config provider so we just go over this again we built a custom fetcher function which uses fetch and basically it returns a promise which is after it gets the response it converts it to JSON which is also a promise then what we did is we wrapped a global provider SW our config around our crimes component crimes component its job was basically to go and fetch the data handle some error in loading States and then pass that data on to another component whose job is to just display this data so it receives the crimes and a unique list of the different categories we did that using this set trick and then in here this is just straight-up react it really has nothing to do with SWR but we received the crimes and the categories we provide a way to filter them and then we filter out the data sort of prior to being rendered and then we we were showing the different filters and a way to reset it and then we're just outputting the data here next up would basically be to take this which is just going in a pre and map it out so that you can see where all these crimes are taking place hope you enjoyed this video check out SWR it's a really cool package and I would I would say I would use this over sort of raw thatch or Axios anytime I was working with a RESTful API I'm not yet sure if I would replace Apollo with this because Apollo provides a ton of nice graph QL specific things but you can do graph QL with this if you're using just a library like graph QL request you can pass in your graphical query and which is cool it's an alternative to Apollo I guess alright that's it have a good day everyone take care
Info
Channel: Leigh Halliday
Views: 22,385
Rating: undefined out of 5
Keywords: react, javascript, programming
Id: oWVW8IqpQ-A
Channel Id: undefined
Length: 18min 11sec (1091 seconds)
Published: Mon Dec 16 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.