javascript / expert
Snippet
Composable Factories for Configurable Logic
A Composable Factory is a higher-order function that returns a customized composable. This allows you to encapsulate shared configuration (like a base URL or auth headers) at an application level while exposing flexible logic for individual components.
snippet.js
1
2
3
4
5
6
7
export function createFetchComposable(baseUrl) {return (endpoint) => {const data = ref(null);fetch(`${baseUrl}${endpoint}`).then(r => r.json()).then(v => data.value = v);return { data };};}
vue
Breakdown
1
export function createFetchComposable(baseUrl) {
The factory function that accepts configuration parameters.
2
return (endpoint) => {
Returns a new closure (the actual composable) bound to the configuration.
3
return { data };
Exposes the reactive state to the consuming component.