I can't understand why I'm getting this error. I am trying to use the Vuex store in a composition function but it keeps throwing me this error about inject (I'm not even using inject). My app makes an await api call to the backend and if there is an error calls my composition function.
[Vue warn]: inject() can only be used inside setup() or functional components.
inject @ runtime-dom.esm-bundler-9db29fbd.js:6611
useStore @ vuex.esm-bundler.js:13
useErrorHandling @ useErrorHandling.js:5
checkUserExists @ auth.js:53
Here is my composition function
import { useStore } from 'vuex'
function useErrorHandling()
{
const store = useStore() // <-- this line
function showError(errorMessage) {
console.log(errorMessage)
}
return { showError }
}
export default useErrorHandling
If I remove this line then it doesn't throw that error
// const store = useStore() // <-- this line
UPDATE: this is how the function is called.
/**
* Check if a user exists in database
*/
static async checkUserExists(data)
{
const { env } = useEnv()
const { jsonHeaders } = useHTTP()
const { showError } = useErrorHandling()
try {
let response = await fetch(`${env('VITE_SERVER_URL')}/auth/check-user-exists`, {
method: 'POST',
body: JSON.stringify(data),
headers: jsonHeaders,
})
if (!response.ok) {
let errorMessage = {
statusText: response.statusText,
statusCode: response.status,
body: '',
url: response.url,
clientAPI: 'api/auth.js @ checkUserExists',
}
const text = await response.text()
errorMessage.body = text
showError(errorMessage) // <-- here
return
}
response = await response.json()
return response.user_exists
} catch (error) {
alert('Error occured!')
console.log(error)
}
}
Functional components defined as a Single-File Component in a *. vue file also receives proper template compilation, Scoped CSS and hot-reloading support. To denote a template that should be compiled as a functional component, add the functional attribute to the template block.
To handle dependency injection in Vue, the provide and inject options are provided out of the box.
Vue 3 introduced the setUp function. It enables us to extract repeatable parts of components into reusable pieces of code. These reusable codes are stored in the form of a function. This function can be used by any component. Its function scope helps us store and protect data.
The error is telling you that useStore
is only for use inside of components, since the module isn't a component. From the docs:
To access the store within the setup hook, you can call the useStore function. This is the equivalent of retrieving this.$store within a component using the Option API.
To use the store
in a module, you can import { store }
from the module where it was created:
store.js
export const store = createStore({
...
})
Other module
import { store } from './store'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With