The "settings" injection was not located. The Vue composition API is encountering problems with providing and injecting

I'm encountering an issue while attempting to pass a reactive object using Vue's provide and inject method. I keep receiving the warning message

[Vue warn]: injection "settings" not found.
and when I try to log out settings, it shows up as undefined.

Can anyone point out what I might be doing incorrectly?

To demonstrate the problem, I've created a simple CodeSandbox.

If you have any insights on why this is occurring, please share with me!

Cheers!

Test.vue

<script>
import { defineComponent, provide, reactive } from "vue";

export default defineComponent({
  setup() {
    const settings = reactive({
      theme: "light",
      color: "#F092AD",
      id: 69,
    });
    provide("settings", settings);
    return {};
  },
});
</script>

App.vue

<template>
  <pre>{{ settings }}</pre>
</template>

<script>
import { defineComponent, inject } from "vue";

export default defineComponent({
  setup() {
    const settings = inject("settings");
    console.log(`settings → `, settings);
    return { settings };
  },
});
</script>

Answer №1

When working with components, it's important to remember that you can only provide data to a component's descendants using the provide function.

If your component is not a descendant, you may receive a warning because no data is being provided.

To address this, consider using app-level provide like this:

app.provide(/* key */ 'message', /* value */ 'hello!')

Alternatively, you can utilize a global state management tool such as pinia or vuex.

For more information, check out this codesandbox or refer to the following snippet:

const { reactive, provide, inject } = Vue
const app = Vue.createApp({
  setup() {
    const msg = inject("message");
    const settings = reactive({
      theme: "light",
      color: "#F092AD",
      id: 69,
    });
    provide("settings", settings);
    return { msg };
  },
})
app.component('child', {
  template: `<pre><test /></pre>`,
})
app.component('test', {
  template: `<pre>{{ settings }}</pre>`,
  setup() {
    const settings = inject("settings");
    return { settings };
  },
})
app.provide(/* key */ "message", /* value */ "hello!");
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <pre>{{ msg }}</pre>
  <child />
</div>

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

The `this` value is null within an onClick function of a ReactJS component

The issue occurs with the onClick method of <span className="nav-toggle">. The specific error message is: cannot read property setState of null. It seems to be related to the scoping of this or due to the asynchronous nature of the setState method. ...

What is the best way to send an object array from an express function to be displayed on the frontend?

//search.js file import axios from "axios"; export function storeInput(input, callback) { //input = document.getElementById("a").value; let result = []; console.log(input); if (!callback) return; axios.post("ht ...

How can you access the input value from load dash's debounce function in a Vue.js application?

Is there a way to capture the input entered during the @typing event of the b-autocomplete component in Buefy? During the @typing event, the debounce method is called with specific parameters as shown below- <b-field label="Location"> ...

What is the process for uploading an image using fetch?

After just starting to learn react, I decided to create a gallery App. However, I am facing an issue when trying to post pictures to the API. Whenever I click on the ADD button, nothing happens except for an error 500 being logged in the console. Below is ...

Endless loading on NodeJS server local host

My NodeJS setup is serving files, but the page seems to be stuck loading. Here's a snippet from my index.js file: const express = require("express"); const path = require("path"); const http = require("http"); const socke ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

Created computed getter and setter for Vue models (also known as "props") using the syntax of Vue Class Component

After exploring the limitations of v-model in Vue 2.x in this Stack Overflow thread, I discovered a way to connect parent and child components using v-model. The solution proposed is as follows: --- ParentTemplate: <Child v-model="formData"> ...

An error occurred due to a class being instantiated within a module, resulting in an overflow of the

On line 7, the console.log statement prints out correctly. host.js "use strict"; var engine = require('./engine.js'); var base = require('./base.js'); var player = new base.Avatar(); console.log(player.x); class PillarGame extends ...

Retrieving information from a JSON file using AngularJS

Hello, I am a beginner in Angularjs and I am facing an issue while trying to retrieve data from a JSON file. The output I am getting is quite strange. Below are snippets from my controller.js and services.js files: angular .module('app') .contro ...

Explore nearby directories by utilizing the HTML file API in conjunction with JavaScript

Exploring the idea of developing an application that utilizes the HTML5 file API and JavaScript to accept a directory path as user input, allowing for the processing (text search) of all files within that directory and its subdirectories. Instead of my cu ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

Exploring the properties within a MongoDB document using mapping functionality

I am trying to retrieve data from a document using Node.js and encountering an issue where the map operator is returning data with similar names twice. I am wondering if I can use filter instead of map to address this problem. Here is the code I am using t ...

Issue with res.redirect not functioning as expected

I am having some difficulty with the use of res.redirect() in my express application. After searching through other questions, I haven't found a solution that directly addresses my specific issue or is detailed enough to be useful. app.get(/\d& ...

Setting up authorization levels for roles in Discord.js

Hi everyone, I came across this script that deals with users posting invite links. How can I whitelist specific channels to prevent the bot from banning or kicking users for posting invite links? Any help would be greatly appreciated. Thank you. adminCli ...

What is the best way to retrieve the value of the hidden fields once the radio button has been selected?

I am currently attempting to retrieve the value of the hidden input fields each time a radio button is clicked. The code provided shows a single div structure, but there are multiple divs with the same structure. While I have been able to successfully ca ...

What is the best way to assign an ngModel dynamically using a dot-separated path?

I have noticed a few questions that are similar to this one, but my question has a slight variation. In my controller, I have an object that resembles the following: $scope.data = { foo: {bar: 1, bas: 2}, biz: 3, blat: 4 }; My goal is to c ...

Pressing the icon will trigger a top-sliding dropdown mobile menu to appear

How can I ensure my mobile dropdown menu slides in from the top when the user clicks the "header-downbar-menu" icon and slides out to the top when clicked again? Currently, the button only shows the menu but I am struggling with writing the JavaScript for ...

Issue with Parcel 2 - Error encountered: Module 'axios' not found

I have enrolled in a Udemy course called 'Node.js, Express, MongoDB & More'. The instructor uses parcel v1 in the course, but now that parcel has released v2, I am facing issues installing v1. I am attempting to access the file from the dist dire ...

Utilizing Vue instance data within components: A step-by-step guide

When using some data defined in a vuejs instance, an error message is displayed: Property or method "url" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. Here is where the ...

Strategies for removing duplicate vertices in geometry through Three.js updates

Currently, I am facing an issue with changing vertex positions in my mesh using three js. It appears that three js stores duplicates for each vertex in the mesh. In my specific scenario, I have 4 duplicates of a vertex, and when I modify one using mesh.g ...