What are Composables?
Composables
Composables are JavaScript functions that:
- Use Vue’s Composition API (ref, computed, watch, etc.)
- Encapsulate reusable reactive logic
- Can be shared across multiple components
- Follow the
use*naming convention
useGetData Composable
TheuseGetData composable handles HTTP requests using Axios:
src/composables/useGetData.js
Return Values
getData(url)
getData(url)
Type:
(url: string) => Promise<void>Description: Async function that fetches data from the provided URLParameters:url- API endpoint to fetch from
- Sets
datos.valuewith response data - Sets
error.valuetotrueif request fails - Sets
cargando.valuetofalsewhen complete
datos
datos
Type:
Ref<any | null>Description: Reactive reference containing the API response dataInitial Value: nullUsage:error
error
Type:
Ref<boolean>Description: Reactive reference indicating if the request failedInitial Value: falseUsage:cargando
cargando
Type:
Ref<boolean>Description: Reactive reference indicating if the request is in progressInitial Value: trueUsage:Usage in Components
Basic Usage
src/views/PokeView.vue
Multiple API Calls
You can create multiple instances of the composable:src/views/PokemonsView.vue
Reactive Fetching
Fetch data reactively when parameters change:State Flow
The composable manages three states during the request lifecycle:1. Initial State
1. Initial State
2. Loading State
2. Loading State
3. Success State
3. Success State
4. Error State
4. Error State
Template Patterns
Common template patterns when usinguseGetData:
Loading, Error, Success
With Empty State
Advantages of Composables
Benefits
Reusability: Same logic can be used in multiple componentsOrganization: Separates business logic from component templatesTestability: Composables can be tested independentlyType Safety: Works well with TypeScriptFlexibility: Easy to customize and extend
Best Practices
Always Handle Loading States
Always Handle Loading States
Show feedback to users while data is loading:
Always Handle Error States
Always Handle Error States
Provide clear error messages when requests fail:
Check Data Before Rendering
Check Data Before Rendering
Use optional chaining and nullish coalescing:
Reset State on New Requests
Reset State on New Requests
Consider resetting error state when making new requests:
Extending useGetData
You can extend or modify the composable for specific needs:Adding Retry Logic
Adding Request Cancellation
Next Steps
Project Structure
Learn about the codebase organization
State Management
Understand Pinia stores for global state