You are using useFetch WRONG! (I hope you don't)
Summary
TLDRIn this video, the host explores common misuses of the 'useFetch' composable in Vue.js, demonstrating how improper usage can lead to unintended API calls. They present a demo application with a login form to illustrate the issue and its resolution. The video clarifies the difference between 'useFetch' and '$fetch', emphasizing that 'useFetch' should be used at the top level in the script setup block, not in event handlers. It also introduces a pattern for using 'useFetch' with an 'execute' function for controlled data fetching, offering solutions to prevent excessive API requests and ensuring optimal application performance.
Takeaways
- 😀 The video discusses common misuses of the `useFetch` composable and its consequences in a Vue.js application.
- 🔍 The presenter demonstrates how misuse can lead to unintended API calls, using a simple login form demo application.
- ⚠️ A key issue highlighted is using `useFetch` directly in event handlers or functions, rather than at the top level in the `<script setup>` block.
- 🛠 To fix problems caused by misuse, the video suggests using `$fetch` directly for simple data fetching without the reactive features of `useFetch`.
- 💡 The presenter explains that `useFetch` is designed to react to changes in reactive values, which is not desired in all scenarios, like form submissions.
- 📚 It's recommended to use `useFetch` at the top level in the `<script setup>` block to leverage its reactivity for data that needs to be refreshed.
- 🔧 For non-reactive data fetching, such as form submissions, using `$fetch` with a try-catch block is shown as a clean solution.
- 🔄 The video also introduces a pattern to use `useFetch` in a controlled manner by disabling its automatic execution and providing an `execute` function.
- 👍 The presenter encourages the use of `useFetch` for data that needs to be reactive and `$fetch` for straightforward data fetching tasks.
- 📝 A rule of thumb provided is to use `$fetch` for button clicks and form submissions, and `useFetch` for data that requires server-side rendering and reactivity.
Q & A
What is the main issue discussed in the video regarding the use of 'useFetch'?
-The main issue discussed is the misuse of 'useFetch' as a data fetching function instead of a composable, which can lead to unintended API calls and performance issues.
Why does the video creator suggest avoiding using 'useFetch' in event handlers?
-Using 'useFetch' in event handlers can cause multiple API calls due to its reactivity, as it watches the reactive values and triggers calls on changes, which is not desired in such scenarios.
What is the alternative to 'useFetch' suggested in the video for handling form submissions?
-The video suggests using '$fetch' for form submissions, as it does not have the reactivity of 'useFetch' and will only make a single API call when invoked.
How can one prevent 'useFetch' from watching reactive values in the video's context?
-To prevent 'useFetch' from watching reactive values, one can set 'immediate' to false and 'watch' to false, which stops the composable from executing immediately or watching the reactive values.
What is the purpose of the 'execute' function in the context of 'useFetch'?
-The 'execute' function, also known as a 'refresh' function, is used to manually trigger 'useFetch' without its reactivity, allowing for controlled API calls when needed.
Why does the video emphasize the importance of calling 'useFetch' at the top level in the script setup block?
-Calling 'useFetch' at the top level ensures that it is used as a composable and not within event handlers or functions where it could lead to unintended side effects.
What is the recommended approach when dealing with API calls for service head rendering?
-For service head rendering, 'useFetch' is recommended as it can handle reactivity and provide benefits like pending state, but it should be used carefully to avoid misuse.
What is the role of the 'onResponse' function in the demo application shown in the video?
-The 'onResponse' function in the demo application is used to track the number of API calls made, helping to demonstrate the impact of using 'useFetch' incorrectly.
How does the video demonstrate the misuse of 'useFetch'?
-The video demonstrates the misuse of 'useFetch' by showing how it can lead to an increasing number of API calls when used within an event handler, instead of making a single call as expected.
What is the significance of the 'Network Tools' in the video's demonstration?
-The 'Network Tools' are used to visually track and demonstrate the number of API calls made, which helps to illustrate the consequences of misusing 'useFetch'.
Outlines
🚀 Introduction to Fetch Misuse
The speaker begins by welcoming viewers back to the channel and wishing them a Happy New Year. They introduce the topic of the video, which is about how to misuse the Fetch API and the consequences of such misuse. To illustrate this, a simple demo application with a login form is presented. The application consists of an app view and a custom API endpoint that simulates a login process. The form is designed to send a username and password to the API upon submission. The speaker highlights a potential issue with the current implementation and sets up a scenario to demonstrate the problem using the Network Tools in a browser.
🔍 Analyzing the Fetch API Misuse
The speaker proceeds to demonstrate the misuse of the Fetch API by submitting the login form and observing the network activity. They notice an unexpected behavior where the API is called multiple times as they type, which is not the intended functionality. The speaker then dives into the code to identify the issue, explaining that the Fetch composable is not being used correctly. They clarify that the Fetch composable should only be called in lifecycle hooks or at the top level of the script setup block, which is not the case in the current implementation. The speaker also points out that the reactive nature of the Fetch composable is causing the issue, as it watches for changes in the reactive values and triggers API calls unnecessarily.
🛠 Correcting Fetch API Usage
To correct the misuse of the Fetch API, the speaker suggests using the non-reactive version of Fetch, referred to as 'dollar fetch'. This approach avoids the issues caused by the reactivity of the Fetch composable. The speaker modifies the code to use 'dollar fetch' and demonstrates that the API is now called correctly, only when the login button is pressed or the enter key is used. They also discuss an alternative approach where the Fetch composable can be used with certain configurations to prevent unwanted API calls. This involves setting the 'immediate' and 'watch' properties to false and providing an 'execute' function for manual API calls. The speaker concludes by emphasizing the importance of using the correct pattern for Fetch API usage, especially in event handlers, to avoid unintended API calls and potential performance issues.
Mindmap
Keywords
💡Composable
💡Fetch API
💡Reactivity
💡Event Handler
💡Lifecycle Hooks
💡Script Setup Block
💡API Calls
💡Use Fetch
💡Dollar Fetch
💡Execute Function
Highlights
Introduction to a new year and a discussion on how to misuse Fetch and its consequences.
Explanation of a simple demo application with a login form to illustrate the misuse of Fetch.
Demonstration of how the application is supposed to work with the login form and API.
Observation of unintended API call repetition when using Fetch incorrectly.
Analysis of the code to identify the mistake in using Fetch as a composable.
Clarification on when and where to use composables versus functions in Vue.js.
Discussion on the misuse of Fetch leading to multiple API calls due to reactive values.
Solution to the problem by using the dollar fetch instead of the use fetch composable.
Explanation of how dollar fetch works and its appropriate use cases.
Demonstration of the corrected application behavior with dollar fetch.
Further exploration of the consequences of misusing use fetch in event handlers.
Introduction to an alternative pattern for using use fetch with immediate false and watch false.
Explanation of how to use the execute function returned by use fetch.
Recommendation to use dollar fetch for button clicks and form submissions.
Emphasis on the importance of not calling use fetch in event handlers to avoid unintended API calls.
Conclusion and a call to action for viewers to share their experiences and ask questions.
Transcripts
hey everybody welcome back to the
channel and happy New Year at least if
you're watching when that video comes
out or rather in that time frame anyway
I hope you had a few great holiday a
little bit of rest never hurts right and
yep it starts again another tip when it
comes to next and today we'll have a
look how you might misuse use Fetch and
what consequences it have let's
[Music]
go use is a very powerful composable and
it's pretty amazing what you can do with
it but there are also few misconceptions
that we want to tackle and see how you
can avoid them for that once again I
built a very simple demo application
with login form to show you the problem
and how you can avoid it let's have a
look this application just consists of
an app. View and also a custom API in
point for some fake login API the idea
is that we have some username and
password saved that will then um be used
as a body and be sent to the login
API when the form has been submitted and
then after everything went through we
can do some things so everything after
here is like some custom logic and also
here we have an on response function
that just increases the call count here
to see how many calls to the API we're
actually doing and then in the template
part we just have a login the form that
will actually call the unsubmit function
and also prevents the default action
then we have some inputs with the data
1p ignore so my password manager won't
bother a login button to submitted and
just some debugging here and maybe
you've seen already what uh is a bit
strange here but um well if not I will
show you in a little bit first let's
have a look at how it works so here we
are the simple login form and we can try
with the password but first I'll open
the Network Tools increase a little bit
and we'll try with maybe
password uh we push login and we see
post request let's see ah didn't work
too bad wrong username password that's
unfortunate did it work false and amount
of course one so let's just try Hunter
to wait whoa whoa whoa whoa what wait
wait wait
wait this was this was a bit
much 9 10 11 the API calls are
increasing now every time I write
something and we also see it in network
tab like all these requests to the login
API is did did I did I break it it's KN
broken did we did we mess up
something yeah we did we messed up
something but KN is not broken no
worries this is what happens when you
use use fetch not as a composable but
just as a data fetching function let's
check out the code and see where the
mistake is and how to fix them here in
line 14 we use the mighty use fatch
composable and in a previous video I've
already talked about what a composable
is and what a function is if you haven't
watched that please have a look at it
it's really worth it as usual on top
right corner I have linked that also in
the description and after the video or
maybe even before you know that
composable should only be called in life
cycle hooks which is very unusual but
more commonly other composes or in the
script setup block or function like in
the setup function or script setup block
but on the top level and this is not
happening here right we don't call this
on the top level so this is the first
problem and the second problem is is we
don't really need your composable we
just use use fetch because it's a bit
convenient to fetch data but what we
eventually want to use we just want to
fetch data we don't need eror to be
reactive we don't need like data to be
ref and so on so on and most importantly
use fetches clever we pass in the body
composed out of the username and
password right and use fetch can be used
for an amazing multitude of things like
oh if a query parameter change like if a
page number change please refetch data
automatically because use fetch will
watch all the reactive values given to
it through like body pams query and so
on so this computed body here that we
pass
along is amazing but in our case we
don't really want that it watch is that
at all so using use fetch in um some
kind of event handler on submit function
so everything that's not really top
level in the script setup block is a
problem and how to solve this pretty
easy we just use dollar fetch right so
here we say okay let's just get the data
out of here and we could even say Let's
uh wrap a try catch around that and say
okay if that worked all fine otherwise
if there there's an arrow we can catch
it and do something with it
like log it or um deal with it
otherwise and that would be the correct
way of dealing with it because now we
don't need a composable in here we just
want the fetch data that's right dollar
fetch will not do any magic behind it
you can't like do refresh calls or
anything this is just of fetch from the
njs repository the package behind that
will just do a call and it's W around
the fetch API which is Prett convenient
you still can use on response you still
can set the method the rest will stay
the same because use fetch is a
composable wrapped around dollar Fetch
and with that things will just work out
let's jump back to the browser and have
a look so in here I trve password again
and we see the call goes in doesn't work
and now it takes it one call all easy
and if I get the right password well
let's see
nope
nope nope it's fine the amount of calls
will only happen when I actually push
the button or uh when I H the enter
key so this is how it should work and
once again misusing these composes is
very common but it can cause severe
issues if we go back one more time and
change the code back to the use fetch um
option there and
and like let's clear the network Tab and
I show you something else let's give a
wrong password in and now we have two
calls right like sorry one call per per
tab one call when I change it if I
submit it again now we have two calls
when changing it and again again again
and now a crazy amount of calls just by
typing one letter I get another five
calls why well because use fetch will
create new composer ible instance that
will watch the reactive information like
the body that we had before when you
call it unsubmit and it's very difficult
to actually clean that up again so
that's also another reason why I don't
want to call composes in these functions
because you can't really clean them up
again and some of them might not work
because they need some context around it
and so on so on but with use fetch you
might think okay but it's it's super
helpful why can't I use it when I want
to fetch data and the answer is you can
there is a pattern that allows you doing
that uh I personally don't use it that
much but in some scenarios it can come
in really really handy let's have a look
going back to the use fatch code here
what we can do is we can take this code
out of the unsubmit function we can move
it up like
here and from here we can say okay you
know what let's move that away
too um let's get the data out here as
well and in here we say immediate false
so we say please use fat should not be
executed straight away and another thing
we can do is we can set watch to false
here so all these things like the body
in this case they won't be watched so it
won't be triggered automatically again
and now what we can expose is an execute
function also known as a refresh
function these are both exactly the same
just named differently and we can call
this execute function down here wait
execute and then we can check for the
arrowed value and
continue and you might now wonder okay
why is this fine then while why can't we
just like leave it in there because we
still call a function right and the
difference is that the function returned
by use fatch that execute function here
this is not a composable this is just
return value of of composable which is a
function and that's totally fine to use
it's actually encouraged right it's very
common to say oh I got some data Maybe I
want some new one so I have some kind of
execute or refresh function once again
it's exactly the same just named
differently for semantic reasons and
yeah just call that here so that
shouldn't be a problem and with that
approach you could still use all the
benefits of use fet like also pending
State and so on so on while keeping all
Al together once again I would not
always suggest that approach it depends
a lot on your structure and architecture
but these are two ways to deal with the
easiest way is once again just rely on
dollar fetch if especially if you want
to submit a post request that's also the
rule of thumb suggestion I I have so
what I would recommend is if you have
some kind of button click
form anything else than a get request
use dollar fetch or a wrapper around
dollar fetch if you need to send some
authorization headers bar tokens and so
on so on right if you have data that's
necessary for service head rendering use
use fetch of course no problem and you
have no issues refreshing it but very
importantly make sure that you never
ever call use fetch in a function like
an event handler a subid function and so
on so on you only want to call it top
level in your script setup block
that's all for today I hope that helped
and that might help you fix some weird
ideas why calls are happening twice
Trice and so on did you ever did a
similar thing let me know and if you
have any questions as usual drop them
down below in the comments that's it for
today I hope to see you next week again
also have a look around the channel
check the other videos if I haven't seen
them and uh Happy hacking see you soon
bye-bye
[Music]
oh
Ver Más Videos Relacionados
5.0 / 5 (0 votes)