Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 819
Martin Zeltin Avatar asked Oct 25 '25 04:10

Martin Zeltin


1 Answers

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.

like image 184
Estus Flask Avatar answered Oct 26 '25 18:10

Estus Flask