Having trouble with Vue 3 Composition API's Provide/Inject feature in Single File Components?

I am currently developing a VueJS 3 library using the Composition API. I have implemented Provide/Inject as outlined in the documentation. However, I am encountering an issue where the property in the child component remains undefined, leading to the following error in the browser console:

https://i.stack.imgur.com/2Y6jw.png

Below is a simplified version of my code:

Usage In Project

<ThemeProvider>
    <Button color="green">
        ABC
    </Button>
</ThemeProvider>

<script>
    import { ThemeProvider, Button } from 'my-library'

    export default {
        name: 'SomePage',
        setup() {...},
    }
</script>

ThemeProvider.js (Parent Component)

import { toRefs, reactive, provide, h } from 'vue'

export default {
    name: 'theme-provider',
    props:
        theme: {
            type: Object,
            default: () => ({...}),
        },
    },
    setup(props, { slots }) {
        const { theme } = toRefs(props)

        provide('theme', reactive(theme.value))

        return () =>
            h(
                'div',
                {...},
                slots.default()
            )
    },
}

Button.js (Child Component)

import { inject, h } from 'vue'

export default {
    name: 'Button',
    setup(props, { slots }) {
        const theme = inject('theme')
        console.log(theme)  // returns undefined

        return () =>
            h(
                'button',
                {...},
                slots.default()
            )
    },
}

Answer №1

Encountered the same warning and issue while using async setup()

The error message stated that inject() can only be utilized within setup() or functional components.

The root cause was found to be an asynchronous call happening before the inject was initialized, though the reason for this requirement is unclear.

The solution involved declaring the inject prior to invoking the async function.


import getCharacters from "../composables/characters";
import { inject } from "vue";

export default {
  async setup() {
    const store = inject("store");
    const { characters } = await getCharacters();
    
    store.updateChars(characters)

    return {
      characters,
      store
    };
  },
};


Answer №2

If you are facing a similar issue, the code itself may not be the problem. In my case, the issue stemmed from different versions of 'vue' and '@vue/compiler-sfc' (Vue compiler for Single File Component) listed in my package.json file.

https://example.com/image.png

Answer №3

[Vue warn]: inject() is restricted to use only within setup() or functional components.

Encountered the same warning when integrating vue-router into the pinia store, had to reorganize the initialization of pinia and router to resolve it.

Attempted to invoke pinia store actions in the main.js file of the router before it was fully initialized.

Tried calling a toast action from another store within this store view image reference here

The initial setup looked like this view image reference here

Updated version to view image reference here

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

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

JavaScript has been used to modify a cell's URL in jqGrid

Currently, I am utilizing struts2-jqgrid along with JavaScript. After the jqgrid has finished loading, it retrieves <s:url var="updateurl" action="pagosActualizar"/>. Subsequently, in the HTML view source, jqgrid generates options_gridtable.cellurl = ...

Changing the structure of a webpage in real-time and inserting new elements into the document

I have a custom x-template filled with a survey element (including a text field and radio button). Upon loading the screen, the database sends a JSON object to the UI based on previously stored sections. This JSON object is then used to populate the survey ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

Employees are unable to operate within an HTML page embedded in a WPF project

When running scripts on an HTML page, the page tends to freeze until the script completes. This is why I am considering using workers. However, I have encountered a problem: <html> <head> </head> <body> <button onclick="startWor ...

Navigating through nested JSON objects in React to display data effectively

I have been struggling for hours to find a solution to this problem with no success. I really need your assistance. The task at hand involves looping through a JSON file and creating a user interface that consists of multiple columns, each containing vari ...

Interact with parent function from child component using data attribute in Vue.js

I have a parent component called Waypoint that contains child elements. I want to be able to call functions on these child elements from the parent component. How can I achieve this? //coding example //template <Waypoint> <div :data-wp-cb ...

Ways to eliminate all characters preceding a certain character within an array dataset

I am currently working on parsing a comma-separated string retrieved from a web service in my application, which contains a list of user roles. My goal is to convert this string into an array using jQuery, and I have successfully achieved that. However, I ...

Is there a way to show a loading indicator while waiting for ajax to finish loading?

While waiting for my messages to finish loading, I'd like to display a loading spinner. The loading spinner is implemented in my Message.vue: import backend from '...' export default { mounted: function() { this.loadMessages(); }, ...

The form created using jQuery is not submitting correctly because the PHP $_FILES array is empty

Creating an HTML form dynamically in jQuery and submitting the form data via Ajax to 'add_sw.php' for processing is my current challenge. However, I have encountered an issue where the PHP script cannot access the PHP $_FILES variable as it turn ...

Unlocking the secrets of accessing data props from a different component in Vue.js

I am working with a component called nabber/header that has some props. I need to insert these props into the component and then pass them onto another component. How can I retrieve this data in order to use it for CRUD operations on a database? Is it feas ...

AngularJS and adding to an array in the routing process

I'm currently working on creating a contact list with two different views. One view displays all the contacts and includes an option to add a new contact, which is represented by a button rather than a space to input information directly. The other vi ...

Switch the array's value if the key is a match?

I'm currently facing an issue where my code does not push the object when the key matches. How can I update the value of the key instead when there is a match? this.state.data.concat(items).filter(function (a) { return !this[a.key] && (th ...

React JS is having trouble rendering an object that contains a list as one of its elements

I've been attempting to display the P_words list element with React using map: const f_data = { key: 2412, reviewed: 100, rating:4, P_words: [{ word: "Coolx", freq: 5 }, { word: "Dumbf&quo ...

Res.redirect() function does not redirect the browser URL as expected when triggered by a request made through a frontend fetch() call

Encountering a new issue that is challenging me. In the backend, there is an API route that redirects the browser URL to /signin using res.redirect('/signin'). Upon this redirection, React Router triggers the rendering of a 'log back in&apos ...

Leveraging JavaScript Functions in HTML

I am having an issue with a JavaScript file containing two similar functions that are executed through an HTML form. While the first function runs smoothly, the second function does not display correctly. It seems like I might be calling or executing the ...

Submit information from an HTML form to a PHP script and then send the response back to the client using AJAX,

Looking to run a PHP script using AJAX or JavaScript from an HTML form and then receive the results on the HTML page. This is what my changepsw.php file looks like: <?php // PHP script for changing a password via the API. $system = $_POST['syst ...

Is there a way to retrieve the $state object from ui router in the console?

I attempted to modify the route from the console by using this method to access the $state object: $inject = angular.injector(['ng', 'ui.router']); $inject.get('$state').go Unfortunately, I encountered an error: Uncaught Er ...

Press on the button that is currently in your field of view

I have a web page with multiple buttons inside div elements. I am looking to automate the process of clicking the "Buy" button that is currently visible on the screen when the user presses the B key. $(document).keydown(function(e) { if (e.keyCode == ...

Creating a Validation Form using either PHP or JavaScript

I need to create a form with the following columns: fullname, email, mobile, and address. If the visitor fills out the mobile field, they should only be allowed to enter numbers. And if the visitor fills out the email field, they should only be allowed to ...