Misusing useFetch in Vue

Jul 12, 2024

Lecture Notes: Misusing useFetch in Vue

Introduction

  • Presenter's Greeting: Happy New Year! Hope you had a good holiday season.
  • Topic Overview: Discussing common misuses of useFetch in Vue and the consequences.
  • Demo Application: Simple login form example to illustrate the issue and solution.

Demo Application Structure

  • Components:
    • app.View
    • Custom API endpoint for a fake login API
  • Functionality:
    • Username and password saved and sent to API upon form submission.
    • Custom logic post-submission, including API call count tracking and response handling.
  • Template Part:
    • Login form that calls an onsubmit function, prevents default action.
    • Input fields with data-lpignore to avoid password manager interference.
    • Login button and debugging elements.

Identifying the Problem

  • Issue: Multiple API calls made on each character input after initial submission.
  • Observation: Network tab shows increasing number of API calls with each input.
  • Reason: Misuse of useFetch as a data fetching function within an event handler.

Understanding useFetch

  • Definition: A powerful composable for data fetching in Vue.
  • Common Mistake: Using it inside functions like onsubmit instead of within lifecycle hooks or top-level script setup.
  • Consequences: Multiple instances are created, causing reactivity issues and multiple API calls.

Correct Usage

  • Composables: Should be called in lifecycle hooks, script setup block, or other composables, but not in event handlers.
  • Solution:
    • Replace useFetch with $fetch for simpler data fetching when reactivity is not needed.
    • Use try-catch blocks to handle API calls and error responses properly.

Implementation Example

  • Original Issue: useFetch used within onsubmit, causing numerous API calls.
  • Fixed Approach:
    • Move useFetch call to the top level.
    • Use $fetch within the onsubmit method.
  • Advanced Fix:
    • Utilize immediate: false and watch: false options with useFetch.
    • Expose execute (or refresh) function for manual fetching.

Practical Tips

  • When to use $fetch:
    • For button clicks, form submissions, or anything other than GET requests.
  • When to use useFetch:
    • For data required for server-side rendering or when reactivity is needed.
    • Always at the top level of script setup, never in event handlers.

Conclusion

  • Summary: Avoid common pitfalls with useFetch by understanding proper usage contexts. Use $fetch for simplicity in event-driven data fetching.
  • Call to Action: Share experiences, ask questions in comments.
  • Closing: Invitation to check out other videos and happy coding.