Composables

useErrorToast

Watcher su Ref<string | null> che chiama una callback toast quando l'errore cambia. Cleanup automatico via setup scope Vue.

Signature

function useErrorToast(
  errorRef: Ref<string | null>,
  showToast: (message: string) => void,
): void

Sostituisce il pattern duplicato watch(error, ...) presente in molte viste. Il watcher è creato nel setup scope del componente chiamante, quindi Vue 3 gestisce automaticamente il cleanup all'unmount.

Parametri

ParamTipoDescrizione
errorRefRef<string | null>Ref di errore monitorata (tipicamente da useCrudResource.error)
showToast(message: string) => voidCallback che mostra il toast (DI: implementazione fornita dal MFE)

Comportamento

  • Osserva errorRef con watch().
  • Quando il valore cambia in qualcosa di non null e non stringa vuota → chiama showToast(newError).
  • Quando torna a null o '' → non fa nulla (no toast di "OK").
  • Cleanup automatico all'unmount del componente (watch nel setup scope).

Esempio base

<script setup lang="ts">
import { useToast } from 'primevue/usetoast'
import {
  useMfeContext,
  useCrudResource,
  useErrorToast,
} from '@pzeta/mfe-contracts/composables'

const ctx = useMfeContext()
const toast = useToast()

const resource = useCrudResource<Cliente, CreateClienteRequest>({
  resourceName: 'clienti',
  loadItems: async () => (await ctx.http.get<Cliente[]>('/api/clienti')).data,
  createItem: /* ... */,
})

// Mostra automaticamente un toast quando resource.error cambia
useErrorToast(resource.error, (msg) =>
  toast.add({ severity: 'error', detail: msg, life: 5000 }),
)

await resource.load() // se fallisce, resource.error si aggiorna e parte il toast
</script>

ErrorToastOptions

Il tipo ErrorToastOptions è esportato ma non passato direttamente al composable corrente. È un'interfaccia "di servizio" che il MFE può usare per standardizzare il proprio wrapper toast.
interface ErrorToastOptions {
  title?: string
  life?: number
  severity?: 'error' | 'warn' | 'info'
}

Pattern consigliato — wrapper centralizzato nel MFE:

// shared/showToast.ts
import { useToast } from 'primevue/usetoast'
import type { ErrorToastOptions } from '@pzeta/mfe-contracts'

export function useShowToast() {
  const toast = useToast()

  return (message: string, options: ErrorToastOptions = {}) => {
    toast.add({
      severity: options.severity ?? 'error',
      summary: options.title ?? 'Errore',
      detail: message,
      life: options.life ?? 5000,
    })
  }
}
// nella vista
const showToast = useShowToast()
useErrorToast(resource.error, (msg) => showToast(msg, { title: 'Errore clienti' }))

Combinato con useCrudView

useCrudView accetta una callback showErrorToast solo per errori save/delete. Per errori di load() è ancora utile useErrorToast:

const resource = useCrudResource({ /* ... */ })
const view = useCrudViewFromResource(resource, {
  showErrorToast: (msg) => toast.add({ severity: 'error', detail: msg, life: 5000 }),
  /* ... */
})

// Toast anche per errori di load()
useErrorToast(resource.error, (msg) =>
  toast.add({ severity: 'error', detail: msg, life: 5000 }),
)

Pattern: severità dinamica

const error = ref<string | null>(null)

useErrorToast(error, (msg) => {
  const severity = msg.toLowerCase().includes('warning') ? 'warn' : 'error'
  toast.add({ severity, detail: msg, life: 5000 })
})

Vincoli

Deve essere chiamato in setup scope (<script setup> o setup() function di un componente Vue). Altrimenti watch() non avrà un'istanza componente per il cleanup automatico → memory leak.

Tipi correlati