I have a vue.js app where I'm using PrimeVue for the UI. I want to have util functions for displaying toasts, but it doesn't seem to work. I have everything set up, but I'm getting the error 'No PrimeVue Toast provided!'.
<template>
<Toast />
<div class="app-container">...
and the utils file:
//toastUtils.ts
import { useToast } from 'primevue/usetoast';
export function showError(message: string) {
const toast = useToast();
toast.add({
severity: 'error',
summary: 'Error',
detail: message,
});
}
I'm including it in the component where it's supposed to be used:
import { showError, showSuccess } from '../../utils/toastUtils';
...
showError('Failed to fetch sales channels.');
it was working when I had the useToast() method directly inside the component, but with these utility functions it doesn't work anymore. Why is that?
Instead of calling useToast()
inside your utility function, call it in the component where the utility function is used, and then pass the toast instance to the utility function. For example:
Updated toastUtils.ts
:
import { ToastServiceMethods } from 'primevue/usetoast';
export function showError(toast: ToastServiceMethods, message: string) {
toast.add({
severity: 'error',
summary: 'Error',
detail: message,
});
}
export function showSuccess(toast: ToastServiceMethods, message: string) {
toast.add({
severity: 'success',
summary: 'Success',
detail: message,
});
}
Component:
import { useToast } from 'primevue/usetoast';
import { showError, showSuccess } from '../../utils/toastUtils';
export default {
setup() {
const toast = useToast();
const handleError = () => {
showError(toast, 'Failed to fetch sales channels.');
};
return { handleError };
},
};