Syntax Video
Build react useFetch from scratch | with check list, tests and examples
- 0:00 intro
- 3:14 repo setup
- 3:30 example hook usage
- 4:46 repo walk-through
- 5:00 test setup
- 5:40 stubbed implementation
- 6:03 call fetch on mount
- 6:46 manage loading state
- 9:11 manage data state
- 10:41 handle options immediate
- 12:30 handle re-renders
- 16:09 handle empty url
- 17:41 handle fetch errors
- 19:12 handle json parse error
- 19:38 handle update calls
- 21:12 handle abort error
- 23:18 resetting state on load
- 24:30 handle multiple requests
- 28:53 cancel request on unmount
- 30:00 thanks!
- 19:29 The test "should handle http errors correctly" has been added to the repo since video release. See notes in src/use-fetch/README.md.
intro
if you want to reuse some logic in your react applications you typically will reach for custom hooks you'll either Implement them yourself or reach for some existing Solutions so there's some really great libraries out there like use Hooks and also use hooks Ts that have all of these built-in Hooks and then there's react use and also beautiful react Hooks and so these libraries are great especially for the kind of things that we do over and over in every react application we potentially don't want to write them from scratch every time but there's a lot we can learn if we do write them from scratch and so in this video I'm going to implement use fetch from scratch and so this is essentially a hook that manages request with fetch but also keeps track of your error State your loading State the data that gets returned from the Fetch and then also handles some more complex scenarios like cancelling of requests and things like that now you might be wondering why would I want to write this from scratch when there are a lot of really good libraries out there essentially this is a great way to practice and get better at writing react code you're going to be using things like use callback use effect use State and you're going to be
pushing them to the limits instead of just your standard basic hooks like use State you're going to really learn how things like use callback and use effect work and so even if you don't want to watch me Implement these I highly recommend you try and build it out yourself so I have this repo here it's called use x and for every one of these videos I create where I create a hook from scratch I have a full test suite and documentation so you can try and implement it yourself so if we take a look at use fetch you can see that I have all of the requirements here and so this describes how our specific Ed fetch Hook is going to work describes all of the arguments what it returns and all of its behavior and you can make sure that your implementation matches all of this Behavior but beyond that I also have tests so aside from just checking boxes in a list it's probably good to have these requirements codified as actual test code and I've done just that so if you want to practice implementing this use fetch function in this way you can just run my test suite and so here I have about 14 different tests that test all of these behaviors and you can pull this repo down and give it a go try implementing the function now if you
take a look at the file here you can see that we have default implementation right I've already defined all of your types I've defined like the basic return and it's kind of up to you to fill this out so you're also going to get a lot of practice with typescript as well you can see that we're using typescript generics and then a few other built-in react types here as well so again this is a great way to level up your skills in react and also in typescript now for every hook that I build from scratch I also provide a solution so if you're trying to get the test to pass but you're running into some issues you can check out the solution of course you're going to have to scroll past the war but beyond that you can see my full implementation and see how I wrote the code to meet all of these requirements now if you're new here welcome this is syntax now we have a podcast hosted by Wes and Scott they publish three episodes every week that dive into all sorts of web development and programming related topics so definitely check it out and then here on the YouTube channel I typically will do deep dives into some of the topics that are covered on the podcast or cover other topics that I find interesting as well like implementing hooks from scratch so
definitely subscribe if that interests you and if you want to see more of these hooks from scratch videos definitely drop a like on the video and let me know what other hooks you would like to see but without further Ado let's write this Hook from scratch my name is CJ welcome to syntax first up let's clone down the repo so I'll grab URL here and then just do a get clone in my terminal here and we'll go into the directory and install dependencies right let's open it up with vs code now in here if you head into the source directory there is a folder for use fetch now in the folder is an example implementation so if you're having a hard time kind of wrapping your mind around how this fetch is even going to be used take a look at the example file because in here we're using the hook so for example we can call use fetch pass in our Pokemon type here and then pass in a URL to get the information about Pikachu and because we have immediate true set in our options here whenever this component mounts it should fire off a request to this URL and then update these State variables
repo setup
example hook usage
accordingly and so if loading is true we're going to show a progress indicator if there's an error we're going to show it on the screen and if we actually have that Pokemon data we're going to render it out here and I essentially am just listing out all the stats and images and stuff like that and then from there our hook also provides a way to change the url or the options dynamically and so it also returns this function called update URL and So within our code we can call that with a new URL and it will re-trigger the Fetch with that brand new URL so you can see here I have a button that says if the URL is the Pikachu URL update it to be the Charizard URL otherwise updated to be the Pikachu URL so it's just a simple toggle back and forth between Pikachu and Charizard but in a real example you might actually have a drop down where you can select the Pokemon that you want and then once they select that updates the URL which then fires off this hook as well so this is the hook that we're going to be implementing today now if you take a look at the readme this has a full checklist of all of the requirements that need to be met in order to implement this hook so you can use this
repo walk-through
as a checklist as you go but all of these requirements directly line up with all of the tests so if you take a look in the test file this file has all of the tests that make sure your implementation of use fetch is meeting all of those requirements now each of these tests uses the it keyword from v test but you can see that right now all of the tests are skipped so from the command line if you do pnpm test you'll see that right now no tests run basically everything is skipped but if we want to start working on our first test we can head in here and then just remove skip from this very first test so these tests are written in a sequential way so I recommend if you're going to use the test Suite to implement your function remove skip from each of these tests one by one as you make the test pass so because I removed skip there the tests are going to rerun and we're going to get a failing test because if you head back over here we can see we have an empty use fetch file now I already have you set up with the proper typings for your return and you can see that we're already accepting the correct arguments but it's up to you to fill in
test setup
stubbed implementation
the details here now I recommend if you're going to try to solve this yourself pause the video here and go write some code go make make those test pass but I am now going to walk through my solution so our first test says it should fetch on Mount by default so our test is looking for a call to the actual fetch function and whenever our component mounts in this case it should call the fetch function so let's do just that now I am going to use a use effect here because I only want to call the fetch once when the component mounts so we'll pull in use effect from react specify an empty dependency array and then in here I'll just call Fetch and we can pass in that initial URL that gets passed into the hook you can see here that I have a linter warning that says I am missing a dependency here I'm going to go ahead and add it because we have tests that make sure we'll do things in the right way as well okay so super basic when the component mounts we call the fetch function and we have one passing test so we can keep moving on from here so first Test passing let's make another one pass I'm going to uncomment this test here we should get a failing test and this one says that it
call fetch on mount
manage loading state
should set loading when fetching data so our hook needs to manage loading State and right now you can see that it's just hardcoding a return of false but we should actually use a state variable for this so I can create a state variable let's call it loading and this is just going to be a use State little default to false and then now we will actually return that state value here and then whenever we attempt to fetch we should set loading to True like so and then afterwards set loading to false now at this point I actually do want to await this fetch because I'm I'm not even doing anything with the return value but I cannot await inside of a use effect so I'm going to go ahead and move move this out into an async function and I'm going to call it load because our hook also exposes a load function so that the user of our hook can reload the data anytime that they want and so essentially I'm going to put all of the fetching logic inside of here and so I'll have an async function and then from there I will set loading to True call Fetch and then set loading to false and so now inside of my
use effect I can actually just call my load function now we should listen to These linter Warnings because again we're missing load as a dependency but watch what happens when we add it as a dependency we get another lter warning and essentially if we Define our functions at the top level like this every single render they get recreated which means that this use effect will get rerun on every render because load gets recreated on every render and so if you look at this linter warning it says it makes the dependency of a use effect hook change on every render so this linter warning is super helpful but essentially it's telling us we need to wrap this in a used callback so that it doesn't get recreated on every render and this is one of the rare cases where yes you actually do need to reach for used call back so let's do it so I'm going to add a used call back right here pass this whole function in pass in my dependency array we'll pull in that from react and then we get a lter warning because we have a dependency on initial URL and so we'll pass that in here but now our use effect is no longer dependent on initial URL it's only
dependent on the load function so this should do it let me just give myself a little bit of breathing room here and while I'm at it instead of just returning a blank function I'm actually going to return that load function that I defined here so this is looking good basically when the component mounts it's going to call load that'll set loading to True call fetch set loading to false is our test passing it is moving right along all right our next test says should set the data after the fetch yeah so at this point test is failing because right now our Hook is returning data as null but we need to actually update it to be the data that we got back from Fetch so inside of our hook right now we're just hardcoding data as null we need a state variable to keep track of this so I'll create a state variable data and then we can do use State and this defaults to null and then our hook will actually return that data here now by default because I initialize this hook as null you can see that it'll only accept the value null I want data to also be type T that is passed in and so
manage data state
if you're new to typescript generics this is a really common use case for generics where essentially we want our fetch to be able to return typed data of any type but we don't know what that type is going to be so we just use this generic t and we can actually use that generic type right here so I can say this data State variable can be of type t or it can be null and if you take a look at our example usage over here we're passing in the type as Pokemon and so Pokemon is just a type that describes all of its properties but essentially by having a generic type parameter like that now the data property that's returned actually has that type so we've set that up now we can actually get that data back from Fetch so I'm going to grab my response here and then we will just parse it as Json so I'll say await response. Json and then we can set our data so right here I'll say set data with our Json data and we've got ourselves a passing test sweet so we're setting the data on to the next test this next one says should not fetch on Mount if immediate is false and so this
handle options immediate
is an option that our custom hook exposes so if you look at that example implementation here we're passing in immediate true we actually want this to be the default option I'm just passing it in in the example so you can see that this accepts an object of options but essentially we want to make it so that someone can use our hook and it doesn't call the fetch function immediately because we also expose this load function we can then allow the user of our hook to call load whenever they think it should be called like in response to a button click or some user event U and so essentially we want to be able to allow them to pass an immediate false and then not call the fetch function on Mount but still be able to call it whenever the load function is called so if we head back over we do have a failing test because right now our test is passing in immediate false but we're still loading the data so let's fix that so you can see that our Hook is also taking in these fetch options which has that immediate property and so what we could do is use it right here and say if options.
immediate is true then call the load function but it's possible that they don't pass in any options at all and we want it to default to true so I'm actually going to put this into a state variable so here I'm going to have options and then set options and then we'll just do a use State and the initial value will be be those options that they passed in but if they didn't pass in anything in this will be undefined and we want to just default it to immediate true like this and so now here inside of our use effect we can say if options. immediate is true then call the load function and so now if options get passed in and immediate is false it will not call that load function whenever the component mounts and in this case you can see that we are missing a dependency so we definitely want to pass that in here as well like so and we have a passing test moving right along now this next one is super important to prevent like infinite render loops and so this test says should not rerun if new options passed in directly so if we take a look at the
handle re-renders
Pokemon example right now these options are being passed in as an object but it's just a bare object right and by the rules of react every time this component renders technically this is going to be a brand new object and so if our Hook was just looking at that object directly it would be a new object on every single render so we want to make sure that we are not just using that value directly we're kind of wrapping it in our own State variable which we've already done instead of using initial options and having a dependency on it directly we wrap it into our own State variable and so now on a render even if a brand new object gets passed in here it's not going to cause an update of our hook because we captured that initial value when the hook was called now the API of our hook actually exposes a function called update options so that from the outside world if the user of a hook does want to change those options they can call this function directly so essentially what we can do is just expose this Setter functions as update options so I'm going to rename it to update options and then return that here and so that looks good for options now
one other thing we need to do is actually pass in the request options here whenever we're making the fetch so we essentially allow the user to pass in a request in it so they can set the method the URL any custom headers or anything like that and so we actually do need to pass that into our fetch so a similar thing would happen right if we pass this in directly then also set a dependency on those request options now when the component renders we're getting a brand new object here so that call back would have gotten recreated and so we can see our tests are failing right now because the tests are simulating a rerender with brand new objects but they're not calling our update function and we actually are rendering so we want to take care of that and we'll do the same thing with request options so essentially we're going to have a state variable that's going to be uh request options and then also we'll expose that update request options fun fun we'll do a use State and I can pass in those initial request options here and so now instead of being dependent on the initial options we can actually use our state variable here so I'll pass it in the dependency array here and I'll pass
it in here and then we can also return this function so we're essentially exposing that updator function so if the outside world needs to update the request options or the options they'll call that function directly instead of passing in a new value okay so this looks good but there's one more update we need to make Can you spot it because our tests should still be failing yeah our tests are still failing and that's because we also need to handle the URL and so if this gets called again with a different URL for our implementation we don't want to recall the fetch now you could create a use fetch function that works in that way but essentially I want to expose an update URL function just like I did for these others so that if the user of our hook needs to change the url in response to some user action they can call that function directly so again we need another state variable we're going to call it URL and we're also exposing that Setter function so that they can update the URL if they would like to so here we're going to say a use State it'll be set to the initial URL and now we'll use our state variable
here instead of the initial URL that got passed into the hook and then of course we can expose our update URL function as well and so we'll return that here and so now we should have some passing tests so essentially the test were rendering the component with new values passed in every time and making sure that it's not actually making a new request even though the arguments here change because the only way to actually update the request is to call these functions directly and we have tests for that later on that'll make sure that these update functions work in the right way okay so we head back over we have a passing test awesome now our last test here is should set error if the URL is empty now this is just implementation specific but in this case we just want to throw an error if for whatever reason they pass in an empty URL like this and so if we run the tests we can see that right now it's actually attempting to fetch uh even though the URL is empty and so we'll actually handle that here inside of our load function we'll just say if the URL is empty then we want to set an error so if you look at our test they're checking to see did we set the
handle empty url
error property to be empty URL so they're explicitly looking for that string so right here I need to set an error variable and so this is one more internal State variable that we're going to call error so here we'll grab our error and then set error and this is going to be a state variable that starts off as null but can also be a string so this is another scenario where we need to type Union so it can be a string or null and then here if there was not a URL we'll say set error we'll pass in that specific empty URL err and then in this case we don't want to fetch at all we want to set the error and then be done with it so I'm just going to do an empty return so if our Hook is called with an empty URL it just sets the error doesn't set loading or anything else and now that we have our error value we should actually return it from our hook so here we're going to return that and while I'm thinking about it I should have done this during the last test but we also have this internal State variable which is like the current URL set and we want to expose that to the outside world as well Okay so we've got that now if we take a look at the tests they're passing because if the URL was empty we set the error we don't set
loading we don't call fetch or anything else like that awesome now I would wager that most of you that have implemented a hook like this at home or at work or wherever you write your custom hooks have probably stopped here but we need some error handling right what happens if fetch throws an error what happens if parsing Json throws an error we are not handling that case so for this hook hook to work well in a lot of different use cases we need to make sure that we handle those errors so if we head back over to the tests we've got our error handling suite and our first one is it should handle network errors correctly so essentially if fetch throws an error we should handle that and so if we take a look at our test Runner uh we get a very weird error because there is an unhandled rejection essentially when our hook calls fetch it's immediately throwing a network error and we're not handling that and the way to handle that is with a tri catch so I'm actually going to wrap this in a tri catch like so and then if there was an error I'm going to set it as the error message and so when you're using typescript the type
handle fetch errors
of this error here is unknown we know that the only type of thing that gets thrown is an actual error object so I'm going to put it into a variable with that type so I'm going to say error is e as capital e error because if fetch throws an error that's going to be a capital e error if there's a parsing error here that's going to be a capital e error and so now that we have an error object we can for instance get access to like the message value and that's what we'll do so right here I can say set error and then just pass in error.
message and so if fetch throws an error and the message is network error that's the error message that we're going to see here great and with that we have a passing test now our next test make sure that we handle Json parse errors correctly um and we should still be fine because if either one of these throw an error we're still setting our error message here uh but there's a difference between fetch throwing an error and then this response. Json throwing an error and so if we unskip this next test it's actually simulating what if that Json function throws an error not the fetch function throws an error and so with that we're still handling it in the same way okay so our custom Hook is looking pretty good now we actually need to test to make sure that these update functions work so if the outside world calls update URL does it refetch the data um or if they update the op options or if they update the request options is our fetch function going to get recalled so we will uncomment our first test which is should refetch if the URL is updated and it already works because we set it
handle json parse error
The test "should handle http errors correctly" has been added to the repo since video release. See notes in src/use-fetch/README.md.
handle update calls
up earlier right so because we added it to our dependency array here and we expose the update URL function to the outside world when the outside world calls update URL that's going to update this state variable this is going to render it's going to see that that dependency changed and a load is going to get recreated and then from there because this use effect is dependent on load load is going to get reinvoke so because we've already set up these things in this way it essentially already has that behavior where if the outside world calls that function fetch function will get recalled great so that looks good our next one is should refetch if the request options are updated I have a feeling this one's going to pass too yep again because we set up those State variables and then the next one is if options are updated so let's remove the skip from that again the test pass okay lastly should refetch if the load function is called and again we've already set this up in a way where that should work because we've defined this load function here here and we're exposing it from our hook the outside
world can just call it directly and so that's what this test is going to do essentially it's going to load the hook and then afterwards call that load function directly and make sure that it actually did reload the data and again because we exposed that load function we're good to go now at this point you're probably thinking how on Earth could we have more tests we're testing all of the scenarios right we need to think about request cancellation now if you look at the docs for fetch fetch accepts a request in knit right that's the type of the request options that we've defined inside of our custom hook but if you look at quest in nit it also supports a signal option and this signal can be an abort signal so there's this API called the abort controller where essentially the fetch can be cancelled from the outside world so signal gets set to a signal from a boort controller and then even if that fetch is in progress if that signal is aborted it'll stop that fetch mid-flight now if we look at an example here on mdn for the abort signal we can see an example with fetch so they made a fetch request here and then they have an abort signal that
handle abort error
is going to abort in 5 seconds and so if this fetch takes longer than 5 Seconds the abort signal is going to get fired if that's the case the error that gets thrown has a name of a boort error and so for our codes essentially all we need to do is check to see does the error have a name of abort error and if it does the request was aborted and we can handle it in that way so let's do it in our test we're going to uncomment this one so should clear data and not set error when aborted so essentially if the the request was aborted we want to set data to null set loading to false set error to to null essentially reset all of our state if the request was aborted and we can handle that right here so just like in the example we saw over here if the name is abort error handle it accordingly so right here we'll say if error. name is equal to abort error we'll do this otherwise we're actually going to set that error right because if it was a network error or a parsing error we still want to set it but if it was an abort error our specific hook doesn't want to set anything it's a essentially just going to clear out the
data so in this case I'll set data to null and also set the error to null so reset everything if this was an abort error and then we're always setting loading to false and so if the request was in Flight it then throws an abort error the codes here will get run which resets our data and then we'll set loading to false and so with that that test is passing now our next test make sure that we're in a consistent State and so because we provide that load function right the user of our hook can call that load function whenever they want our behavior is that if that load function is called we also want to clear out the state right we want to reset data we want to reset error and so this next test is going to make sure that if load is called again the previous data gets cleared out before it attempts to request the next set of data and so let's unskip this test we have a failing test because it's expecting that data to be null so this is another thing we need to do whenever the load function is called clear out the existing data and now the tests are passing this next one says should clear the existing error if the load function is called so we'll
resetting state on load
unskip this this one so essentially what this is testing is it calls our hook but does it in a way that throws an error and then it calls the hook again and it wants to make sure that the next time it's called that error is actually cleared out and so similar to how we're resetting the data we also want to set the error to null as well and so right here we could just set error to null right above this like that but then potentially I would be setting the error twice if the URL was empty so I'm just going to actually add an lse statement here so if there was not a URL error then we'll set the error to n and like that we have a passing test now these next tests deal with us providing our own abort controller and so essentially what we want to happen is if our load function is called multiple times like in quick succession we actually want to cancel the previous requests right and so we already talked about this abort signal API and so essentially we're going to need to create one of our own inside of this hook so that way if a call to load comes in and a previous request was in progress we can call signal. abort to abort the previous one so let's try to implement this so first
handle multiple requests
we'll uncomment this test should abort previous fetch if load is called while fetching so essentially the hook will make a request for one thing but then while that request is in progress the load function will be called again for a different thing and we need to make sure that that first request is cancelled and we only hold on to the response for that second request so now with this saved you can see the test is failing and the way that it's testing this is we're making sure that the data that got set is the data that got set by the second request because in our example the first request actually responds later and so it actually sets the data to be the response of the first request so the way we're going to handle this is by creating our own abort controller inside of our hook and so for this we need to hold on to that abort controller right because we need to be able to cancel the previous requests inside of the hook so you might reach for used State let's see what this looks like by using used state so let's say I have an abort controller and then we have set abort controller and then we'll do a use State and in this case I'm just going to pass in a new instance of an abort controller now essentially what I need to do is pass in
the signal of this abort controller into our request op options so here I'm going to Define my request in it that's going to be those request options that got passed in but those could be undefined so I'm going to set it to an empty object otherwise because from there I want to set the signal property so we can pass the signal in and we're going to set it to be abort controller. signal and so now if this signal is aborted then this fetch will not complete it'll throw the error and then just do nothing and so for this to work basically anytime the load function gets called it needs to cancel the previous request if the previous request hasn't completed and so the way to do that is just say abort controller. abort so the previous request gets cancelled and then we actually need a new abort controller because you can't abort it multiple times so essentially what we would do is reassign it so here we would say set abort controller to be a new abort controller but you'll see our dilemma because down here we need the latest one and now because we're also using a state variable we actually have to pass that
abort controller in here as a dependency and so that means if we're like setting State inside of something that requires state and its dependency it would it would create like an infinite Loop so the way to get around that is to use a ref instead so instead of storing our abort controller here inside of a use State we're going to do a use ref and now we'll have to access the current value so here I can say abort controller. current and then call abort but now I can override that current value without having to call a set state so here I can say current is a new abort controller like so but down here to get access to that signal I do need to say do current and then here we need to pass in that request and knit instead of the default request options and so now the signal is actually passed into the fetch here and so if it's aborted this fetch is going to throw an error and just like that if this load function is called in quick succession or it's called before this request completes it's going to abort the previous request which will stop this from completing and then create a new abort controller and then
make a new request now another thing we'll do is if the request was aborted we don't want to set our data here because it's possible that we hit like this race condition where it was cancelled but then we're still setting it here so we actually want to check that however we can't just look at current right because every time this gets called We're overwriting current in the current scope of this fetch we need access to the current B controller and not the reassigned one if this method got recalled so I'm going to create a variable called current abort controller and then just set that equal to current here and so now this basically captures that value inside this scope and so if the load function gets called again abort controller. current is going to get overwritten but my local variable here will still be the previous one and then we can do some checks here so here I can say if the signal was aborted then do nothing so essentially you made it past all this but the signal was already aborted now in most cases it'll actually throw while the fetch is in progress and then it'll get caught by our current error Handler but we always want to check for that just in case uh there's some kind of race condition so we'll
save that and now we have a passing test now the very last thing is we also want to abort requests if the component is unmounted so if someone navigates away from this page and there was a fetch in progress we want to cancel that request so let's comment out that last test which is should abort a request in progress if unmounted and the way that we're going to handle that is with our disposal function so use effect can return a function and this is our disposal function so essentially we can do anything here to dispose of resources or in this case cancel a request so this function is going to get called anytime this use effect is torn down so anytime the component is re rendered or anytime the component is unmounted and that's the main reason we need to do this here we're already handling renders because we're canceling the request at the top of the load function here so if the load function is called again we're canceling the previous request but if a request is in progress and then the user navigates away from this page and the component gets unmounted we need to call abort as well and so we'll do just that essentially in our disposal function we
cancel request on unmount
will abort the request in progress and so when the component is unmounted the impr progress request gets aborted and with with that we should have our last passing test nice now that's it for this video but thank you so much for watching now if you'd like to see me Implement other hooks from scratch let me know down in the comments which hook would you like me to implement and there's a lot to choose from so all of these hook resources are going to be linked in the description as well so you can check these out and also if you have your own ideas for custom hooks that maybe aren't in these libraries yet suggest that as well cuz it could be fun to see how I implement it from scratch all right that's it for this one I'll see you in the next one [Music]
thanks!
Quote it with credit and a link. Quoting Syntax