I am using the PrimeVue
ponent library and I try to call useToast()
from inside my own custom position function but it is throwing me this error:
[Vue warn]: inject() can only be used inside setup() or functional ponents.
Here is my position 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 position function in my main.ts
file.
import { useAxios } from '@/services/useAxios'
const { configureAxios } = useAxios()
configureAxios()
I am using the PrimeVue
ponent library and I try to call useToast()
from inside my own custom position function but it is throwing me this error:
[Vue warn]: inject() can only be used inside setup() or functional ponents.
Here is my position 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 position function in my main.ts
file.
import { useAxios } from '@/services/useAxios'
const { configureAxios } = useAxios()
configureAxios()
Share
Improve this question
asked Apr 15, 2022 at 11:05
Martin ZeltinMartin Zeltin
3,2385 gold badges24 silver badges43 bronze badges
1 Answer
Reset to default 4use
posables 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 posable internals.
The error means that this one appears to use provide/inject and so intended to be used strictly inside ponent hierarchy, and it's incorrect to use it any where else. Since toasts are displayed by Toast
ponent, the application should be instantiated any way in order to do this.
In this case Axios interceptor could be set inside a ponent as soon as possible, i.e. inside setup
function of root ponent.