0
0
Vueframework~30 mins

Composable for API calls (useFetch pattern) in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Composable for API calls (useFetch pattern)
📖 Scenario: You are building a Vue 3 app that needs to fetch user data from an API. To keep your code clean and reusable, you want to create a composable function that handles fetching data and managing loading and error states.
🎯 Goal: Create a Vue 3 composable called useFetch that fetches data from a given URL and provides reactive data, loading, and error states.
📋 What You'll Learn
Use Vue 3 Composition API with ref and watchEffect
Create a composable function useFetch that accepts a URL string
Manage reactive variables data, loading, and error
Fetch data automatically when the URL changes
Return the reactive variables from the composable
💡 Why This Matters
🌍 Real World
Creating reusable composable functions for API calls helps keep Vue apps clean and maintainable. It allows multiple components to share fetching logic easily.
💼 Career
Understanding composables and reactive data fetching is essential for modern Vue development roles, improving code reuse and user experience.
Progress0 / 4 steps
1
Setup reactive variables
In a new file, create a composable function called useFetch. Inside it, create three reactive variables using ref: data initialized to null, loading initialized to false, and error initialized to null.
Vue
Need a hint?

Use ref from Vue to create reactive variables inside your composable.

2
Add watchEffect to fetch data
Import watchEffect from 'vue'. Inside useFetch, add a watchEffect that runs whenever url changes. Inside it, set loading to true, reset error to null, then fetch the data from url. On success, set data.value to the JSON response. On failure, set error.value to the error message. Finally, set loading to false.
Vue
Need a hint?

Use watchEffect to reactively run the fetch code when url changes.

3
Return reactive variables
At the end of the useFetch function, return an object containing the reactive variables data, loading, and error.
Vue
Need a hint?

Return an object with the reactive variables so components can use them.

4
Use the composable in a component
Create a Vue component that imports useFetch. Inside the setup function, call useFetch with the URL https://jsonplaceholder.typicode.com/users. Return the reactive variables data, loading, and error from setup. In the template, show a loading message when loading is true, an error message when error is not null, and a list of user names when data is available.
Vue
Need a hint?

Use the composable inside setup and bind the reactive variables in the template with Vue directives.