Async React Hooks

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello hello hello and welcome back to my youtube channel oh you hungry learners out there learners learners so glad to have you back around these parts here's another week another episode another opportunity to kind of talk about some code I always have to be careful about that because there's code and there's tech but tech also includes like hardware like iPhone speaking of which and getting the new iPhone I am very very excited it's got some more higher definition vlog II like videos with my better iPhone camera it's gonna be great today I don't want to have a big preamble because I am going I'm a little over afraid of this video today we're going to be delving deep on a sink react hooks say that five times fast and you will hopefully do better than me I'm gonna be building a little mini jiffy search app from the ground up with no code pre-made so I am terrified beware probably some fancy editing ahead to make sure that the continuity of this video makes sense to both you and me so the goal of this video is just mostly to we're to make an app where you can type in some input hit search and then see a whole bunch of giffy jiff search results gif Jif peanut butter it's all the same to me and we're going to then through this exercise also play with how to make a sync react hooks and I'm curious how far I get because of this video it's longer than 20 minutes then I wouldn't watch it so then I wouldn't expect you to watch it but maybe you will watch it but through a live example hopefully we'll together make and understand how best to write asynchronous react hugs let's get into the code okay and here's where we begin with a lovely blank page whoa okay what do you want to start let's start making the search box and having us being able to submit our queries for Givi so do that we're gonna make everyone's favorite form component we're gonna have an input component in here as well we're gonna have there be a value of search which we're gonna make in a second on change I'm gonna come back to for now placeholder will call this search for gifs and that's about it let's then have this on change be using so on Shane just give it an event and we want to take from that event and pass it to this thing we'll call so search new e current targets not just current targets and what that will do is take from the element the value which is the search query don't do this search query I want to use everyone's favorite og hook there can be any hook that is a Original Gangster hook it's gonna be you state when I call cost search set search and then do you state and by default that's going to be an empty string and we'll save that we will format it and here we have it stretch for gifts like type and I did things wrong I think I got a current target and target it's just target target dot value and now we have this successfully updating with my text that shows you for trying to listen to me to learn these things and then of course we want to do is we're going to have a little button when I have type submit' so that this and then we'll have a say search and then we'll have on here a on submit and this will have our on submit function which will define up here function on submit taking the event object by default we want to prevent the default behavior prevent default because the default form behavior is to refresh the entire page which we don't want we want this to be a jazzy single page app I'm just going to log out the search value let's say that refresh we're gonna tap up hit search ax they get tap up so we can I do that we get a new thing and enter all the things they're good so we have now built a lovely simple form in react with the set with a used stage react hooks all the words together hopefully makes sense let's keep going I'm a little scared okay so now what we want to do is start making API calls when we submit and make this search request so the easy way to do that is obviously with fetch but the API that won't be playing with today is the jiffy API and jiffy in case you are not aware it's a fun little website that lets you search for gifts they have an API for developers to use it you have to make you have to make an app which I already have done with my dashboard right there there's my API key you are welcome to steal it because after I finished making this video I'm going to delete it so that it's not abused and if eaten it gets mad at me but I think it'd be easier just to delete it later then having to try to hide the API key now it's actually made this little bit bigger while we're playing around here so that's the sirens on Manhattan outside always fun luckily I'm not coding outside or you wouldn't be able to hear me at all and what's when I figure out ways of learning new things and especially with an API is by example so here we have an API Explorer where it has a nice little GUI for actually making requests so I'm using this API key again it'll be deleted so you're welcome to play with it because it won't work and use the search endpoint and when I search for cookie my fault I only want ten reading yes I want gee I don't want to show anything's and get have YouTube banned me then we're gonna send a request and we get the response back just lovely huge JSON blob this is the top thing that's the gif that's gonna be fun to play with let's go back here sir is the query and then cookie and then this is 10 this is the URLs and the request again and when I was playing with this before I was tryin understand how I could preview the image and I did some ahead of time thinking just to save us time says we're gonna take from the images the the preview item and that's we're gonna use to actually render the video but this is the actual API request right here so I'm gonna copy and paste this to make this smaller again shrink or linka I'll see if in keeping to go back to it and here we're gonna do we're gonna say whenever we submit the search query we're gonna see this in another state variable and when do this for demonstration purposes mostly male voice you could do this but for now we'll focus on async reax hooks so this is what we're gonna use for demonstrating this i'm gonna call this query we're gonna call it a set query and then we're gonna go into here and then save the search query when we submit the form so like for example we want to make a starter use effect hook just start things off to see things working correctly it's import use effect with a comma because commas make the world go round we're gonna call this console a lot of this i'm gonna log the query variable a little hack actually a little developer pro tip if you want to easily have a label for a variable that you're logging you can expand it as an object using the es2015 plus object shorthand notation syntax so in this case log you'll see in a second what it looks like I'm gonna delete this console logs only has one console so what this should do when I save the page is we can type in the search value and then when we actually hit enter we'll hit submit it's gonna call the on submit handler which lets me just inline this because I'm a huge fan of than lying things I want to call this e just like that we can get rid of that so when you hit on submit we're gonna prevent default so it doesn't do a page navigation and then we're gonna call set query to see if the search in the new query object which we're gonna be console logging here if you see my other videos about use effect this version is having no dependencies define so this should be logged every time this component rerender so I'm gonna save the file page few loads and here I have by default an empty query as I've had been here oops that is running every time right yes that is correct it's running every time because we have their dependencies in the user effect dependency argument so I typed in cookie hit enter now it says cookie but now it's gonna spam cookie so we don't want that you could start off by having them to you right right that'll have it load once but that's not going to help us either because when we have an empty array as the dependency it's going to only look it's only going to render this effect when the component first renders and here we actually even say that we have an es Lynch rule that says that we're missing a dependency query so we're going to say isn't here whenever the query variable changes then run this effect essentially we're saying when the query state changes I want to I want to run this effect with the components but I save that refresh is I attacked my heart's content only want to hit enter do things change so this is nice and I'll to worry about stamina yeah I call things are nice and things are nice and controlled which is lovely I'm only running at once so now what we want to do is that when this effect runs when this query is updated we want to actually call the API to actually get that data so I'm gonna go back to here I'm gonna go up to the very tippy top and grab this request URL right here or copy and paste it I'm just gonna make a little helper function for myself because this function is very long no I won't listen to it online so here we have this use effect it's only being ran when the query state changes so let's do the a naive implementation of how you make a sync we have to hook this is the wrong way and we'll see why in a second so we're gonna use this be a sync because we want this function to be async I want to say try catch for async await or to say response equals fetch here with this huge long string because I my font increased it shows way off the page we're using the query variable here so we're gonna replace this query of cookie with query right there so we got this response value back and then what we want to do we really care about the error is fleet this console.log we have this response we also want to do gonna parse the response object with JSON so I'm gonna say we're gonna call this left response and we're gonna call this and then we'll do a contra spawns I'm not gonna call conscious on equals response dot JSON which again we have to await this because these are asynchronous functions and then we have this JSON objects will just log that for now I'm gonna use this from a little trick so now I'm gonna save this and by default we have an error from the built-in Lynton well this is actually built into react and it's actually saying an effect function must not return anything besides a function which is used for cleanup however it looks like you used an async function which returns are promised by default an async function returns a promise you should not do that instead write that async function inside the use effect and then call it immediately like this and the reason for that is because react worries that if you were right affects this way it could lead to erase conditions and mismanagement of state and UI in your application if things get rapidly called effects should be synchronous and this is kind of how you work around that limitation so for now what we're gonna do is I'm going to wrap this entire so we can see here a sink fetch data I'm just gonna do exactly what they tell me do and I'm gonna say a sync function touch data and I'm just going to take all this content inside of it put it inside here remove this async value and then immediately call fetch data and then also what I realized is that this is running on page load which I don't really need it to because this doesn't give me anything so I'm gonna say query if query doesn't equal an empty string then we'll call fetch data so let's see if that cool so no errors so far I searched for cookie look at that no errors from react itself and we have back here this JSON object which has indeed a property and this data property has all the results from here and what I actually want is I want the I'm actually gonna take this and see this into another state variable so let's actually go into here and call this results set results equals u States and this is going to be an empty array by default and we want to take this set results I'm gonna say it set results we want this to equal json dot data dot and then what we actually do this data is an array but all I really want was that in images there is this preview object that I want so I actually want to take this data which is an array I'm gonna map it to have each item and each item is this big object this is the object I'm gonna say return item dot images then all I want is the preview and then all I want is the mp4 so what this will be set to what I call results is just an array of those strings to the mp4 values so I save that cool let's start rendering this just to see if this works we're gonna go over here here's my form let's make a little break line cuz I love my old old fashioned VR and we're just gonna have this beam napping over the results run a map over I'm gonna call this item and for now all I want to do is just render each of these in an h3 so nice to item is all I have and I'm gonna need a key as well obviously let's see if that so now if I search for cookie okay things are showing up things are looking correct but this is working right this is all looking good I mean two longest JSON anymore that's fine and I haven't here this this is let's finish off the results in the UI it's always love me some UI I'm gonna use the video element which I don't use nearly enough it's a self-closing component the source is the item and then there's two other atras dominant dude that makes things look nice and fun is a autoplay and loop okay so let's save that and search for cookie oh my god we have some cookies in our console website we are not making an asynchronous call whenever this changes so if this is still there I didn't call this banana look at that potassium intensifies I feel my potassium intensifying already to review we have in here a input element which is keeping track of its own state with search and then when you actually submit the form around here either by hitting Enter or hitting the search button we called the on submit handler which is insane that search query that starts value to this cert to the query value and then we have our use of our asynchronous use effects function such that whenever the query value the query state value changes it'll call this effect and all this effect actually does is right here it's just calling another function and this is where we do things asynchronous which is awesome this is mostly what we need to be aware of is that when you want to run an asynchronous function there's two things you have to be aware of one the effects itself cannot be a synchronous react doesn't like that it can cause issues this is really distracting refresh the page react doesn't like that it can cause your UI to get out of sync with your data management waste conditions the other thing is when you need to have asynchronous function is to in line that asynchronous function inside especially if you're using the wonderful react hooks eeeh Slynt plugins that's what so for example I go back here under an empty array that is what has this morning right here this react folks it was awesome DAF Depp's is a rule rules with hook right here yes Len plug-in react close if you are using react folks doesn't recommend you install this plug-in because it makes it's kind of like having a tutor for how to learn and use hooks correctly but by having the a sweetness function in line it allows this yes then plug-in to work we very much could have taking all this yanked it out move it to the top here and then passed in a query variable right there right like this and then just returned this value so let's do this right here a little fun refactor between this and when I call set results remove that and call this data then results I'm just gonna pass instead results think that's gonna work fine [Music] this should still work maybe yeah it does I don't know why there's plain for maybe but what's interesting is that if I were to do this well it does still have missing dependency because it's see me use it here if I had done this then I have successfully tricked the eslint plugin because it doesn't see me using it anywhere so by having these things be in line to actually have a direct dependency about what you're using the es Lim plugin can help you with that which we take things a little bit further make a custom hook for making a request against the jiffy API yes is that what I hear you say yes you want to custom hook little mini lesson let's do it we're going to call here or do a new thing called function use euphy and then here we're to pass a new query because all that this custom hook will take in is the actually just go a little back because this is gonna be a lot easier if I actually had this working when the Easter in this function was in line these effects book and you'll see why in a very quick second make sure that everything's still working work yes things are still working oh that's my story of my life right there I have to work for money or make a new custom hook called use giving and all its gonna take in is a query and then here's what I'm gonna do when would take all this out and put it in to here ah yeah so use giffy and use giffy is going to return back results and we're passing here the query which means that I'm gonna actually yank this up into here and then here we have set results results and we're going to return [Music] results okay let's save this let's test it and it still works so what I've done here is I haven't here this you Skippy which is passing this query and whenever this query changes then this results is going to change so all this internally in here is the same but if I play all that side-effect logic of having to manage how to call the API in here has managed entirely inside of here so we had this new Skippy and I've literally just moved some code around but now if I wanted to use to get a PAP I in multiple components I can just use this one line which is this is really the power of hooks you have all this the only side effects you can then just extract as self-contained units functionality and then use wherever you want so again all it's doing I have a user effects book in here that's saying when the great change is which is being passed into here - then call this fetch data and then set the result internally - here in the local you state of this use giffy custom hook and then malicious featuring the results so by default it's gonna get empty array and when this effect run and calls such data and call set results it's going to that updates that results here return the results which will be returned here which would render here and then get us nice and happy with our results and because we have everything self-contained it means that we can potentially show more functionality into this custom hook because it's nice and self-contained like there's no if I have a battery return nothing what I can actually do here it's actually have like a loading state so I can actually have here say loading set loading when I say you state is false it's by default it's not loading I'm gonna have this return a object now of loading it's the second argument so here it's loading as well that's the value I'm gonna pretend that if it's loading I'm gonna say loading this a should we do give me gifts or I will render the results like that so here I have this loading so when we first make the call when I say set loading is true and then I'm actually gonna call this and finally which actually means that this this runs no matter what so either it runs after the try statement finishes or the cash statement finishes but I just want to make sure that I always set loading to false when things are done so I want to save this and I say banana give me gifts you saw that for a second there yes give me gifts and now I have States being contained inside this custom hook and you can kind of build out from there that error states all these things you can just really build out this this really nice rich custom hook okay that was a pretty deep dive into how to write asynchronous react looks with a nice fun real world example I'm always a fan of when you get real examples to actually show up why and how you'd want to use these react features in your everyday work remember a use effect cannot the function pass to use effect cannot be itself asynchronous you can't have two nested inside of that and after that you kind of off to the races it also makes making a custom async react hook that's four buzzwords custom async react hook for your own usage across your entire location hopefully that was something new that you hadn't already known please do share with your friends then leave loved ones and your co-workers are probably the ones that would be most appreciated these videos if you are not REM subscriber of this YouTube channel do me a favor and yourself a favor and hit that subscribe button smash that button through those things that is set in irony but also in all earnestness because every one of those subscription counts helps me spread my learnings and knowledge with everyone out there they're also welcome to become a patreon patron at patreon.com slash HS wolf to donate money to making these videos I look forward to seeing you again next week with a brand new video and until then have fun hugging
Info
Channel: Harry Wolff
Views: 41,383
Rating: 4.8403139 out of 5
Keywords: react hooks, react, hooks, async react hooks, tutorial
Id: HQq5Sod8AEk
Channel Id: undefined
Length: 25min 36sec (1536 seconds)
Published: Mon Sep 23 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.