When working with Vue 3, remember that inject() function is only allowed within setup or functional components

I'm puzzled as to why I keep encountering this error. I am attempting to utilize the Vuex store in a composition function, but for some reason, it keeps throwing an error regarding inject (even though I'm not using inject at all). My application makes an API call to the backend and if there is an error, it 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 the code snippet of 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 comment out that specific line then the error disappears

// const store = useStore()  // <-- this line

UPDATE: This is how the function is invoked.

/**
     * 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('An error occurred!')
            console.log(error)
        }
    }

Answer №1

The error message indicates that the useStore function should only be used within components, as it is not meant for modules. According to the documentation:

To access the store in the setup hook, you can utilize the useStore function, similar to accessing this.$store in a component using the Option API.

If you need to use the store in a module, you should import { store } from the file where it was created:

store.js

export const store = createStore({
...
})

Another Module

import { store } from './store'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

changing the color of arrows in Vue Slick Carousel: a simple guide

I am currently using the vue-slick-carousel plugin for a carousel feature in my project. I am trying to customize the color of the arrows without modifying the default styles provided by the package itself. However, the code snippet I added to the main C ...

Determining the spatial capacity of a mesh using ThreeJS surpasses the volume of its bounding box

Issue at Hand: The challenge lies in the fact that the bounding box volume is turning out to be smaller than the volume calculated from the mesh. Attempts So Far: To begin with, I computed the volume of a bounding box using the following code: //loaded ...

Tips for modifying the background color of all elements ahead of the element I have selected within a grid

https://i.stack.imgur.com/cW4Lp.png I'm trying to achieve a functionality where clicking on the 20th numbered block changes everything before it to light orange. I have a sandbox code snippet attached and would appreciate any guidance on what needs t ...

The feature for sending posts in Angular.js appears to be malfunctioning

I have developed a rest-API for adding todos in a MongoDB database. When I use Postman with the setup below, I can successfully save instances: http://localhost:3000/api/addtodo x-www-form-urlencoded with values text="Test", completed: "false". However, ...

Creating SVG paths using coordinates for THREE.js

I copied the exact code from this ThreeJs Example designed for generating a three-dimensional City Model. I've created an SVG path outlining city boundaries using Google Maps and now I'm trying to use the above code to create a similar 3D object ...

Click event triggering smooth scrolling

I am currently working on implementing a smooth scrolling effect using the React JavaScript library without relying on jQuery. My goal is to ensure that when a user clicks on a link, they are directed to the specific section of the page seamlessly. The f ...

Is there a simple and efficient method to transition the loading of a regular website to AJAX for the entire site?

Is it feasible to easily and quickly change all links on a website to load the URL that the user clicked via AJAX, rather than refreshing the webpage? My website currently has standard links, but in order to create a mobile application for iPhone, I need ...

How can recursion be implemented when the items are interdependent?

I am looking to create a function that can generate a list of individuals upon whom a specific person relies. The complexity here lies in the fact that these individuals may, in turn, rely on the original person. To illustrate: const people = { ' ...

The data visualization tool Highchart is struggling to load

As I try to integrate highcharts into my website, I encounter an unexpected error stating TypeError: $(...).highcharts is not a function. Below is the code snippet in question: @scripts = {<script src="@routes.Assets.at("javascripts/tracknplan.js")" ty ...

A Javascript/JQuery event that prevents Chrome from loading insecure content

When a page is loaded over HTTPS but the resources are served from an HTTP website, Chrome will display an "insecure content" warning. Is there a way to detect when Chrome has blocked insecure content and if the user has allowed it? There is a shield icon ...

Error in Angular: Http Provider Not Found

NPM Version: 8.1.4 Encountered Issue: Error: Uncaught (in promise): Error: Error in ./SignupComponent class SignupComponent_Host - inline template:0:0 caused by: No provider for Http! Error: No provider for Http! The error message usually indicates the a ...

Deactivate tag Script using JQuery

Is there a way to dynamically remove two <script> tags from a page at the document ready event? Each tag is assigned its own unique id. I attempted to use the following code: $("#idPrimoScript").remove(); $("#idSecondoScript").remove(); However, t ...

Using an array as the source for your Mui Autocomplete instead of JSON

I'm attempting to recreate the autocomplete MUI example shown here, but with a slight variation. Instead of utilizing a JSON data structure, I am simply passing an Array. Here is what I have tried: export default function SearchTutorialArray() { con ...

When a user focuses out of a field, an event object will appear within it

Currently, I am developing a VueJS application that enables users to modify JSON files containing specific data. In my project, I have implemented two similar components: AliasEntry and EquipmentEntry. The latter is responsible for manipulating an array of ...

Is there a way to refresh a Material-UI data table in React whenever a user takes any action?

I am facing an issue with my Lock-Unlock button and delete button. The problem arises when I render data from axios using the useEffect hook, it works fine. However, if I try to lock or unlock a user, the table does not update automatically. This indicates ...

"Patience is key when waiting for the alert dialog response in Vuetify

I currently have a reusable component called Alert.vue. <v-dialog v-if="alertDict" v-model="alertDict.showDialog" max-width="460"> <v-card> <v-card-title>Title</v-card-title> & ...

Cypress - simulate multiple responses for watchPosition stub

I have a small VueJs app where clicking on a button triggers the watchPosition function from the Geolocation API to retrieve the user's position and perform some calculations with it. Now, I want to test this functionality using Cypress testing. To ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

Observing Node.js processes to track the peak memory usage of each process

Is there existing monitoring software that can track newly spawned node.js processes on my machine and display the maximum memory usage when the process ends? If not, how can this be achieved effectively? I have identified the specific Node.js processes I ...

Create a server directory structure that populates multiple HTML dropdown lists using either jQuery or AJAX

As a novice navigating jQuery and Ajax, I find myself faced with a specific challenge. My current situation involves a structured set of directories on a server. My goal is to populate a dropdown dynamically with this file hierarchy. Upon click ...