modbender / nuxt-snackbar

A Nuxt Snackbar/Toast Implementation independent of CSS framework
https://nuxt.com/modules/snackbar
MIT License
19 stars 6 forks source link

No Snackbar provided when used in a plugin #19

Closed GreyXor closed 2 days ago

GreyXor commented 2 days ago

Hello

sse.client.ts

import { useServerStore } from "@/stores/server";

export default defineNuxtPlugin({
  name: "my-plugin",
  async setup(nuxtApp) {},
  hooks: {
    "app:created"() {
      const store = useServerStore();

      const evtSource = new EventSource(store.host + "/foo", {
        withCredentials: true,
      });

      evtSource.onmessage = (event) => {
        const snackbar = useSnackbar();

        snackbar.add({
          type: "success",
          text: "log received",
        });
      };
    },
  },
});

In this code, a notification should be triggered each time I got a message from evtSource (what can happens in any time during my app running).

snackbar works in other places in my vues files, but here in this plugin, I can't send notifications because I got this error : Uncaught Error: No Snackbar provided! Any idea ? thanks

modbender commented 2 days ago

Hey this is something previously discussed in #4.

Due to the nature of how snackbar works it can't be used within composable or plugins.

This probably applies to other snackbar packages too. Atleast I have tried primevue and I can't do similar things as you mention with their toast.

But you could try the same thing as mentioned in #4 , maybe using it like

onMounted(() => {
    snackbar.add({
        type,
        title,
        text,
    });
});
GreyXor commented 2 days ago

Hi, thanks for your fast answer.

With https://vue3-toastify.js-bridge.com/ it works as expected even in plugin. I will check with onMounted().

modbender commented 2 days ago

Hmm, I'll take a look into this asap. Maybe turn that into a module too. Looks good.