Martin Zeltin
Martin Zeltin

Reputation: 3198

Vue 3 - inject() can only be used inside setup() or functional components

I am using the PrimeVue component library and I try to call useToast() from inside my own custom composition function but it is throwing me this error:

[Vue warn]: inject() can only be used inside setup() or functional components.

Here is my composition function:

import axios from 'axios'
import { useToast } from 'primevue/usetoast'

export function useAxiosInterceptors() {
    const addResponseInterceptors = () => {
        axios.interceptors.response.use(
            (error) => {
                if (error.response?.status == 401) {
                    showErrorToast(
                        'Session expired',
                        'It looks like you do not have a valid access token.'
                    )

                    return Promise.reject(error)
                }
        )
    }

    const showErrorToast = (summary, detail) => {
        const toast = useToast() // <-------- this causes  the error

        toast.add({
            severity: 'error',
            summary: summary,
            detail: detail,
            life: 3000
        })
    }

    return { addResponseInterceptors }
}

I use this composition function in my main.ts file.

import { useAxios } from '@/services/useAxios'

const { configureAxios } = useAxios()

configureAxios()

Upvotes: 4

Views: 10503

Answers (1)

Estus Flask
Estus Flask

Reputation: 222309

use composables are primarily intended to be used directly inside setup function. It's possible to use some of them outside, but this is decided on per case basis depending on composable internals.

The error means that this one appears to use provide/inject and so intended to be used strictly inside component hierarchy, and it's incorrect to use it any where else. Since toasts are displayed by Toast component, the application should be instantiated any way in order to do this.

In this case Axios interceptor could be set inside a component as soon as possible, i.e. inside setup function of root component.

Upvotes: 4

Related Questions