Files
FabledCurator/frontend/src/composables/useAsyncAction.js
T
bvandeusen a37dad33c7 refactor(dry-F1): shared useAsyncAction lifecycle helper for stores
New composables/useAsyncAction.js owns the loading/error/try-finally
lifecycle. Migrated 11 stores: credentials, downloads, sources, posts
(error=raw) + ml, artistDirectory, tagDirectory, showcase, suggestions,
seriesReader, modal (error=message). The errorAs option preserves each
store's existing error shape so store.error keeps the same type for
components (~50 consumption sites unchanged). Stores whose catch also
reset data (suggestions/seriesReader/modal) clear it upfront instead.

Deliberately NOT migrated (special control flow, would change behavior):
artist (conditional 404 catch + dual loading states), migration (rethrows),
gallery (inflight-id stale-response guard), and the Shape-B no-catch /
loaded-guard / keyed-cache stores.

Net -77 lines.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 12:53:57 -04:00

29 lines
941 B
JavaScript

import { ref } from 'vue'
// Owns the loading/error lifecycle shared by most Pinia stores. `run`
// flips loading on, clears error, runs `fn`, captures any throw into error
// (swallowed so callers can read `store.error`), and always resets loading.
// Returns fn's resolved value on success, or undefined if it threw.
//
// `errorAs` matches each store's existing convention so migrations don't
// change what `store.error` holds: 'raw' keeps the thrown object (the
// ApiError, with .status/.body), 'message' keeps just the string.
export function useAsyncAction({ errorAs = 'raw' } = {}) {
const loading = ref(false)
const error = ref(null)
async function run(fn) {
loading.value = true
error.value = null
try {
return await fn()
} catch (e) {
error.value = errorAs === 'message' ? (e?.message ?? String(e)) : e
} finally {
loading.value = false
}
}
return { loading, error, run }
}