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

Utilizing iOS Local Storage for Efficient Form Submission Handling

I feel like my brain is on the verge of exploding. I just can't seem to get this to work as intended, and I'm struggling to pinpoint the issue. Currently, I have a form that needs to be processed using AJAX. Before proceeding with that, I want ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

Error: Unable to access 'author' property as it is undefined

Currently, I am in the process of learning how to create my own blog by following a tutorial on Github. The tutorial can be found at https://github.com/adrianhajdin/project_graphql_blog. However, while working with [slug].js to build localhost/3000/post/re ...

Steps for retrieving the identifier of a duplicated element

I've copied an element and changed their IDs, but I'm having trouble fetching the IDs of the cloned elements in jQuery. Can someone assist me with this issue? The HTML view source code is provided below: <table id="dataTable" borde ...

Determine the time difference between two dates, taking into account Daylight Saving Time adjustments

If a start date and number of days are given, I need to calculate the end date by adding the number of days to the start date. This is the code snippet I used: var endDate=new Date(startDate.getTime()+ONE_DAY); Everything was working fine until I notice ...

Having trouble importing moment-range into your Angular 4.x application using ES6? Getting an error about incompatible call signatures?

In my Angular 4.x application, I encountered an issue while trying to import the moment-range package. The official documentation suggests using the following code: import Moment from 'moment'; import { extendMoment } from 'moment-range&apo ...

Is there a way to store JSON data in a constant variable using Node Fetch without encountering the error TypeError [ERR_INVALID_URL]: Invalid URL?

In my current NodeJS project, I am working on extracting data from a JSON file and then sending it to a constant variable in my app2.mjs. The goal is to organize this data into an array of objects and eventually save it into a database. However, when tryin ...

The search bar is visible on desktop screens and can be expanded on mobile devices

Check out my code snippet below. <style> #searchformfix { width: 50%; border-right: 1px solid #E5E5E5; border-left: 1px solid #E5E5E5; position: relative; background: #fff; height: 40px; display: inline-block; border: ...

The JQuery mobile navigation menu effortlessly appears on your screen

I am experiencing an issue with a JQuery mobile navigation that is designed for screens @979 pixels wide. The problem arises when the screen is resized to 979px - the menu pops up fully extended and covers the content of the web page. I suspect that this ...

The rendering of graphs in FusionCharts is experiencing delays particularly in Internet Explorer, with Chrome performing more efficiently in comparison

I am currently utilizing FusionCharts to generate and display graphs. My requirement is to load over 60 graphs on a single page. Upon testing the page loading in Internet Explorer 11, it is taking approximately 5 minutes. However, when using Google Chrom ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

Using SASS variables in JavaScript: A guide

My JavaScript file contains a list of color variables as an Object. export const colors = [ { colorVariable: "$ui-background" }, { colorVariable: "$ui-01" }, { colorVariable: "$ui-02" }, ... ] The Object above is derived from a scss file whic ...

Steps for assigning an id to a newly created div within a parent div while in design mode

Imagine creating a div element with the attribute contenteditable="true", and then checking the console for what happens next: 1st. In the console, you only see a simple div tag. <div id="typbody" contenteditable="true" style="width:100%; height:200px ...

Error encountered while trying to load component: template or render function is not defined

I have set up a basic vue.js configuration using browserify and vueify. Following advice from previous tutorials, I included aliasify as a dependency to utilize the template engine. Below is my package.json file: { "name": "simple-vueify-setup", "ve ...

Firebase Error: In order to deploy without hosting via source, options must be provided. (app/no-options)

After developing a Next.js application, I integrated Firebase authentication and utilized the useContext hook for managing user state throughout the app. Here's the snippet of code for the AuthContext: auth.js import { createContext, useState, useEff ...

Simple JavaScript numeric input field

Hey there, I'm a beginner learning JavaScript. I'm currently working on creating a program that adds numbers input through text fields. If you want to check out the HTML code, visit this link on JS Fiddle: http://jsfiddle.net/fCXMt/ My questio ...

What is the best way to implement rate limiting or throttling on a Strapi API?

Our company relies on a simple strapi API implemented in node.js and hosted on Heroku. Despite our efforts, we have not been able to find a solution to implement rate limiting, as it appears that Heroku does not offer throttling add-ons and strapi lacks bu ...

"Using SetState frequently results in multiple rerenders of the component

Currently, I am developing a messenger application with a main screen component that displays all messages. My goal is to make sure that whenever a user sends or receives a message, the component updates the Flatlist to show the latest sent message. To ach ...

What is the best way to simultaneously utilize two APIs where one is using HTTP and the other is using HTTPS?

What is the best way to simultaneously use two APIs, one being http and the other https, in Angular or JavaScript? ...

The assignment of ajax success data to variables results in an error because data[0] is not defined

Having some trouble retrieving and assigning data from a database in JavaScript using AJAX to call a PHP script with a MySQL query. Although the AJAX request is successful, when trying to store the data into variables, they appear as undefined or NaN in th ...