[SOLVED] How to create reusable toastService with primeVue toast?

Issue

I want to know if there’s a way to create a reusable scritp/class/service with primevue toast function calls, in such a way that I don’t need to call the primevue toast functions directly in every single component.

What I’ve tried to do up until now, was to create a ToastService.ts like this:

import { useToast } from 'primevue/usetoast';

    const toast = useToast();

    export function addMsgSuccess(): void {
        toast.add({ severity: 'success', summary: 'Test', detail: 'Test', life: 3000 });
    }

But this code crashes my application and I get the following error:

Uncaught Error: No PrimeVue Toast provided!at useToast
(usetoast.esm.js?18cb:8:1) eval (ToastService.ts?73ba:3:1)
Module../src/shared/service/ToastService.ts (app.js:1864:1)
webpack_require (app.js:849:30) fn (app.js:151:20) eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/ts-loader/index.js?!./node_modules/eslint-loader/index.js?!./src/views/cadastro-plano/CadastroPlano.ts?vue&type=script&lang=ts:31:87)
Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/ts-loader/index.js?!./node_modules/eslint-loader/index.js?!./src/views/cadastro-plano/CadastroPlano.ts?

Does anyone know how to solve this problem, or to create functions that make this add() call, so I don’t need to call it everysingle time?

Solution

This solution works for me, but I’m not sure it’s a good solution.

First: export app from main.ts

// main.ts
import {createApp} from 'vue';
import App from '@/App.vue';

import PrimeVue from 'primevue/config';
import ToastService from 'primevue/toastservice';

export const app = createApp(App);

app.use(PrimeVue);
app.use(ToastService);

app.mount('#app')

Second: import app and use toast service with app.config.globalProperties

// myToastService.ts
import {ToastSeverity} from 'primevue/api';
import {app} from '@/main';

const lifeTime = 3000;

export function info(title: string = 'I am title', body: string = 'I am body'): void {
  app.config.globalProperties.$toast.add({severity: ToastSeverity.INFO, summary: title, detail: body, life: lifeTime});
};

export function error(title: string = 'I am title', body: string = 'I am body'): void {
  app.config.globalProperties.$toast.add({severity: ToastSeverity.ERROR, summary: title, detail: body, life: lifeTime});
};

Third: import myToastService in your component.

// myTestToastComponent.vue
<script setup lang="ts">
import {info, error} from '@/components/myToastService';

info();
</script>

Answered By – Nina

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *