You are using useFetch WRONG! (I hope you don't)

Alexander Lichter
5 Jan 202411:14

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

00:00

🚀 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.

05:01

🔍 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.

10:03

🛠 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

A composable is a reusable piece of functionality in a software component, often used in the context of UI libraries or frameworks like Vue.js. In the video, the term is used to describe a powerful feature that can be misused if not handled correctly. The script mentions that composables should only be called in lifecycle hooks or at the top level in the script setup block, which is a key concept for avoiding issues with reactivity and unnecessary API calls.

💡Fetch API

The Fetch API provides an interface for fetching resources, such as making network requests. In the video, the misuse of the Fetch API is discussed, particularly in scenarios where it is used improperly within event handlers or functions, leading to unintended multiple API calls. The video demonstrates how to use the Fetch API correctly to avoid such problems.

💡Reactivity

Reactivity in programming refers to the ability of a system to automatically update the UI in response to changes in the data. The video script discusses how misuse of composables can lead to reactivity issues, such as when a composable is used to watch reactive values like the body of a request, causing unintended side effects like multiple API calls.

💡Event Handler

An event handler is a function that is called when a certain event occurs. In the context of the video, the script points out that calling composables within event handlers can lead to problems because it can create multiple instances that watch reactive information, causing unintended API calls. The video suggests avoiding this by using the Fetch API directly in such scenarios.

💡Lifecycle Hooks

Lifecycle hooks are functions that are called at specific points in the lifecycle of a component. They are used to perform actions at the right time in the component's life. The video emphasizes the importance of calling composables only in lifecycle hooks or at the top level in the script setup block to prevent misuse and ensure proper reactivity behavior.

💡Script Setup Block

The script setup block is a feature in Vue.js that allows for a more concise and readable way to define component logic. The video script uses this term to explain where composables should be called to ensure they function correctly and to avoid issues with reactivity and unnecessary API calls.

💡API Calls

API calls are requests made to an application programming interface (API) to perform certain operations or retrieve data. The video discusses the consequences of misuse of the Fetch API, leading to an increase in the number of API calls, which can be inefficient and lead to performance issues. The video provides solutions to control API calls effectively.

💡Use Fetch

Use Fetch is a composable function used for making API requests in a reactive manner. The video script explains how it can be misused, particularly when used within event handlers or functions, leading to multiple API calls. The video provides guidance on how to use it correctly to avoid such issues.

💡Dollar Fetch

Dollar Fetch refers to a non-reactive version of the Fetch API, used for making API requests without the reactivity features of the composable version. The video suggests using dollar fetch when making API calls that do not require reactivity, such as form submissions, to avoid unnecessary API calls and potential performance issues.

💡Execute Function

An execute function, also known as a refresh function, is used to manually trigger API requests or data fetching operations. The video script discusses how to use the execute function returned by use fetch to control when API calls are made, providing a way to maintain reactivity benefits while avoiding misuse in event handlers.

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

play00:00

hey everybody welcome back to the

play00:02

channel and happy New Year at least if

play00:04

you're watching when that video comes

play00:06

out or rather in that time frame anyway

play00:08

I hope you had a few great holiday a

play00:10

little bit of rest never hurts right and

play00:14

yep it starts again another tip when it

play00:16

comes to next and today we'll have a

play00:17

look how you might misuse use Fetch and

play00:21

what consequences it have let's

play00:24

[Music]

play00:28

go use is a very powerful composable and

play00:32

it's pretty amazing what you can do with

play00:33

it but there are also few misconceptions

play00:38

that we want to tackle and see how you

play00:40

can avoid them for that once again I

play00:42

built a very simple demo application

play00:44

with login form to show you the problem

play00:47

and how you can avoid it let's have a

play00:49

look this application just consists of

play00:51

an app. View and also a custom API in

play00:54

point for some fake login API the idea

play00:57

is that we have some username and

play00:59

password saved that will then um be used

play01:02

as a body and be sent to the login

play01:05

API when the form has been submitted and

play01:08

then after everything went through we

play01:10

can do some things so everything after

play01:13

here is like some custom logic and also

play01:15

here we have an on response function

play01:17

that just increases the call count here

play01:19

to see how many calls to the API we're

play01:21

actually doing and then in the template

play01:24

part we just have a login the form that

play01:27

will actually call the unsubmit function

play01:29

and also prevents the default action

play01:31

then we have some inputs with the data

play01:33

1p ignore so my password manager won't

play01:36

bother a login button to submitted and

play01:39

just some debugging here and maybe

play01:42

you've seen already what uh is a bit

play01:44

strange here but um well if not I will

play01:48

show you in a little bit first let's

play01:50

have a look at how it works so here we

play01:52

are the simple login form and we can try

play01:55

with the password but first I'll open

play01:56

the Network Tools increase a little bit

play01:59

and we'll try with maybe

play02:01

password uh we push login and we see

play02:04

post request let's see ah didn't work

play02:07

too bad wrong username password that's

play02:09

unfortunate did it work false and amount

play02:12

of course one so let's just try Hunter

play02:15

to wait whoa whoa whoa whoa what wait

play02:19

wait wait

play02:20

wait this was this was a bit

play02:24

much 9 10 11 the API calls are

play02:27

increasing now every time I write

play02:29

something and we also see it in network

play02:31

tab like all these requests to the login

play02:33

API is did did I did I break it it's KN

play02:38

broken did we did we mess up

play02:40

something yeah we did we messed up

play02:42

something but KN is not broken no

play02:44

worries this is what happens when you

play02:47

use use fetch not as a composable but

play02:49

just as a data fetching function let's

play02:52

check out the code and see where the

play02:53

mistake is and how to fix them here in

play02:56

line 14 we use the mighty use fatch

play02:58

composable and in a previous video I've

play03:01

already talked about what a composable

play03:02

is and what a function is if you haven't

play03:04

watched that please have a look at it

play03:06

it's really worth it as usual on top

play03:08

right corner I have linked that also in

play03:10

the description and after the video or

play03:13

maybe even before you know that

play03:16

composable should only be called in life

play03:18

cycle hooks which is very unusual but

play03:20

more commonly other composes or in the

play03:23

script setup block or function like in

play03:26

the setup function or script setup block

play03:28

but on the top level and this is not

play03:30

happening here right we don't call this

play03:32

on the top level so this is the first

play03:36

problem and the second problem is is we

play03:39

don't really need your composable we

play03:41

just use use fetch because it's a bit

play03:43

convenient to fetch data but what we

play03:46

eventually want to use we just want to

play03:48

fetch data we don't need eror to be

play03:50

reactive we don't need like data to be

play03:52

ref and so on so on and most importantly

play03:56

use fetches clever we pass in the body

play04:00

composed out of the username and

play04:01

password right and use fetch can be used

play04:05

for an amazing multitude of things like

play04:08

oh if a query parameter change like if a

play04:10

page number change please refetch data

play04:12

automatically because use fetch will

play04:14

watch all the reactive values given to

play04:16

it through like body pams query and so

play04:19

on so this computed body here that we

play04:22

pass

play04:22

along is amazing but in our case we

play04:26

don't really want that it watch is that

play04:28

at all so using use fetch in um some

play04:33

kind of event handler on submit function

play04:36

so everything that's not really top

play04:39

level in the script setup block is a

play04:41

problem and how to solve this pretty

play04:44

easy we just use dollar fetch right so

play04:49

here we say okay let's just get the data

play04:51

out of here and we could even say Let's

play04:53

uh wrap a try catch around that and say

play04:56

okay if that worked all fine otherwise

play04:59

if there there's an arrow we can catch

play05:00

it and do something with it

play05:03

like log it or um deal with it

play05:07

otherwise and that would be the correct

play05:10

way of dealing with it because now we

play05:13

don't need a composable in here we just

play05:15

want the fetch data that's right dollar

play05:17

fetch will not do any magic behind it

play05:20

you can't like do refresh calls or

play05:21

anything this is just of fetch from the

play05:24

njs repository the package behind that

play05:28

will just do a call and it's W around

play05:29

the fetch API which is Prett convenient

play05:32

you still can use on response you still

play05:34

can set the method the rest will stay

play05:36

the same because use fetch is a

play05:38

composable wrapped around dollar Fetch

play05:41

and with that things will just work out

play05:44

let's jump back to the browser and have

play05:45

a look so in here I trve password again

play05:49

and we see the call goes in doesn't work

play05:53

and now it takes it one call all easy

play05:56

and if I get the right password well

play05:58

let's see

play06:01

nope

play06:03

nope nope it's fine the amount of calls

play06:06

will only happen when I actually push

play06:08

the button or uh when I H the enter

play06:11

key so this is how it should work and

play06:15

once again misusing these composes is

play06:18

very common but it can cause severe

play06:21

issues if we go back one more time and

play06:24

change the code back to the use fetch um

play06:28

option there and

play06:30

and like let's clear the network Tab and

play06:32

I show you something else let's give a

play06:34

wrong password in and now we have two

play06:36

calls right like sorry one call per per

play06:40

tab one call when I change it if I

play06:42

submit it again now we have two calls

play06:44

when changing it and again again again

play06:46

and now a crazy amount of calls just by

play06:50

typing one letter I get another five

play06:52

calls why well because use fetch will

play06:58

create new composer ible instance that

play07:00

will watch the reactive information like

play07:02

the body that we had before when you

play07:05

call it unsubmit and it's very difficult

play07:08

to actually clean that up again so

play07:11

that's also another reason why I don't

play07:13

want to call composes in these functions

play07:15

because you can't really clean them up

play07:17

again and some of them might not work

play07:20

because they need some context around it

play07:22

and so on so on but with use fetch you

play07:26

might think okay but it's it's super

play07:28

helpful why can't I use it when I want

play07:30

to fetch data and the answer is you can

play07:35

there is a pattern that allows you doing

play07:37

that uh I personally don't use it that

play07:39

much but in some scenarios it can come

play07:41

in really really handy let's have a look

play07:44

going back to the use fatch code here

play07:47

what we can do is we can take this code

play07:49

out of the unsubmit function we can move

play07:52

it up like

play07:53

here and from here we can say okay you

play07:57

know what let's move that away

play08:01

too um let's get the data out here as

play08:03

well and in here we say immediate false

play08:08

so we say please use fat should not be

play08:11

executed straight away and another thing

play08:13

we can do is we can set watch to false

play08:15

here so all these things like the body

play08:18

in this case they won't be watched so it

play08:19

won't be triggered automatically again

play08:22

and now what we can expose is an execute

play08:26

function also known as a refresh

play08:28

function these are both exactly the same

play08:30

just named differently and we can call

play08:33

this execute function down here wait

play08:37

execute and then we can check for the

play08:39

arrowed value and

play08:42

continue and you might now wonder okay

play08:44

why is this fine then while why can't we

play08:47

just like leave it in there because we

play08:49

still call a function right and the

play08:52

difference is that the function returned

play08:54

by use fatch that execute function here

play08:56

this is not a composable this is just

play08:58

return value of of composable which is a

play09:00

function and that's totally fine to use

play09:03

it's actually encouraged right it's very

play09:04

common to say oh I got some data Maybe I

play09:06

want some new one so I have some kind of

play09:08

execute or refresh function once again

play09:11

it's exactly the same just named

play09:13

differently for semantic reasons and

play09:16

yeah just call that here so that

play09:19

shouldn't be a problem and with that

play09:21

approach you could still use all the

play09:24

benefits of use fet like also pending

play09:26

State and so on so on while keeping all

play09:29

Al together once again I would not

play09:31

always suggest that approach it depends

play09:34

a lot on your structure and architecture

play09:36

but these are two ways to deal with the

play09:38

easiest way is once again just rely on

play09:40

dollar fetch if especially if you want

play09:43

to submit a post request that's also the

play09:45

rule of thumb suggestion I I have so

play09:48

what I would recommend is if you have

play09:50

some kind of button click

play09:53

form anything else than a get request

play09:56

use dollar fetch or a wrapper around

play09:58

dollar fetch if you need to send some

play09:59

authorization headers bar tokens and so

play10:03

on so on right if you have data that's

play10:06

necessary for service head rendering use

play10:09

use fetch of course no problem and you

play10:12

have no issues refreshing it but very

play10:15

importantly make sure that you never

play10:17

ever call use fetch in a function like

play10:21

an event handler a subid function and so

play10:24

on so on you only want to call it top

play10:27

level in your script setup block

play10:30

that's all for today I hope that helped

play10:32

and that might help you fix some weird

play10:34

ideas why calls are happening twice

play10:36

Trice and so on did you ever did a

play10:39

similar thing let me know and if you

play10:42

have any questions as usual drop them

play10:43

down below in the comments that's it for

play10:45

today I hope to see you next week again

play10:47

also have a look around the channel

play10:48

check the other videos if I haven't seen

play10:50

them and uh Happy hacking see you soon

play10:58

bye-bye

play10:59

[Music]

play11:12

oh

Rate This

5.0 / 5 (0 votes)

相关标签
useFetchAPI CallsVue.jsDebuggingWeb DevelopmentComposable FunctionsError HandlingFetch APIVue Composition APIPerformance Optimization
您是否需要英文摘要?