nuxt-community / axios-module

Secure and easy axios integration for Nuxt 2
https://axios.nuxtjs.org
MIT License
1.19k stars 245 forks source link

How to use nuxt from axios plugin #495

Closed jonalxh closed 3 years ago

jonalxh commented 3 years ago

Hi, days ago I was using nuxt in SPA mode and I was able to use fire my own alerts by using $nuxt.alert("message") from my axios.js plugin. Now I'm migrating to SSR mode and my plugin throws me an error saying it cannot access to $nuxt instance.

Can you tell me please how to access the nuxt instance from my axios plugin in SSR mode? Thanks a lot.

devzom commented 3 years ago

@jonalxh can You share the plugin code? You should access the $nuxt instance by using ctx attribute or destructured alert variable from ctx (context)

jonalxh commented 3 years ago

Here's my axios plugin:

export default async ({ app, $axios, $swal, redirect }, inject) => {
    $axios.defaults.withCredentials = true;
    $axios.defaults.mode = "no-cors"
        ...

        $axios.onError(error => {
        if ($swal) {
            $swal("ERROR", error.response, "error)
        }
       }
}

I needed to set the if clause because sometimes the $swal variable doesn't exist, additionally I tried using app.$swal, but result was the same like destructuring it, and by creating a context or ctx destructured variable didn't work.

devzom commented 3 years ago

As I remember Vue.$swal had some issue with SSR. It's just not available on SSR. Found this thread $swal inject in nuxt

jonalxh commented 3 years ago

But I'm using vue-sweetalert2 with the nuxt option.

pi0 commented 3 years ago

If sweet alert module has no SSR support, makes sense adding a check like if (process.client)