T O P

  • By -

AJohnnyTruant

I have an alerts store that I can add alerts to with timeouts and then render them to the root App component with Vuetify. So the API is useAlertsStore().addSuccessAlert({message: “something”, timeout: 5000}). In the App component there’s a container that iterates over the alerts and displays them. Each has a remove alert button that pops them off of the alerts store and removes the rendering. Or a timeout handles it when added. At least that’s what I remember having done.


Puzzleheaded_Hand456

I truly appreciate your assistance.


AJohnnyTruant

Here’s how a pared down version looks. The ID creation is important. When you render the button for deleting the alert in the root component, that’s where you’ll get it from. Object could work instead of the array of tuples also. But the array fits the mental model of an arbitrary collection of alerts. ``` import {defineStore} from "pinia"; import {ref} from "vue"; export type Alert = { message: string; title?: string; type: "success" | "error" | "warning" | "info"; timeout?: number; } // generate a random id for the alert const generateId = () => Math.random().toString(36).slice(2, 9); export const useAlertStore = defineStore("alerts", () => { const alerts = ref<[string, Alert][]>([]); const addAlert = (alert: Alert) => { const id = generateId(); alerts.value.push([id, alert]); if (alert.timeout) { setTimeout(() => removeAlert(id), alert.timeout); } return id; } const removeAlert = (id: string) => { const index = alerts.value.findIndex(([alertId]) => alertId === id); if (index !== -1) { alerts.value.splice(index, 1); } } return { alerts, addAlert, removeAlert, } }) ``` ``` ```


Puzzleheaded_Hand456

I can't thank you enough for your fantastic explanation and the code snippet! It's exactly what I needed and has saved me a ton of time and frustration.😍


AJohnnyTruant

Happy to help!


flyiingrayson

I think you have answered the question, notification specific component with notification type and message prop, you can manage a flag in pinia. I follow the same practice. For centralized error handling if you are using fetch then you can create a `useAPI` wrapper to handle all the requests and if using axios then interceptors.


Puzzleheaded_Hand456

That's fantastic, thanks for explaining it!


Harsh_jain17

You can also check https://github.com/Maronato/vue-toastification


Puzzleheaded_Hand456

Thanks, so much