In Vue 3, the use of provide() is restricted to the setup() function

I've encountered an issue with my AppReplyToMessage component. It's supposed to send data to the AppSendMessage component in order to notify it that the message being sent is a reply. Here's how I'm implementing it: The AppReplyToMessage component:

<script setup>
import { provide } from "vue";
import AppSendMessage from "../AppSendMessage.vue";

let props = defineProps({
    message: {
        type: Object,
        required: true,
    },
});

let message = toRefs(props).message;

const replyToMessage = () => {
    const message = {
        reply: true,
    };

    provide("reply", message);
};
</script>
<template>
  <button@click="replyToMessage">
    Reply
   </button> 
</template>

In the AppSendMessage component, I'm trying to receive the data as follows:

<script setup>
  const reply = inject("reply", null);
</script>

However, I'm encountering an error message stating

[Vue warn]: provide() can only be used inside setup().
in the console.

Answer №1

The use ofprovide

should be primarily at the top level of setup, rather than nested within another function.</p>
<p>To adhere to best practices, start by initializing an empty ref and passing it to the provide function. Then, in your <code>replyToMessage
function, update the value of the ref upon button click.

<script setup>
import { provide, ref } from "vue";

// ...

const reply = ref(null);
provide("reply", reply);

const replyToMessage = () => {
    const message = {
        reply: true,
    };

    reply.value = message;
};
</script>
<template>
  <button @click="replyToMessage">
    Reply
   </button> 
</template>

Documentation

Answer №2

Despite the minor errors in your source code, such as forgetting to include

import { inject } from "vue"
in the AppSendMessage component, there are two significant design flaws that need attention.

  1. Vue props should not be mutated within components as they are readonly.

  2. The Vue warning specifies that provide() should only be called from setup() or from <setup script>.

You are currently calling setup() from a lambda function.

const replyToMessage = () => {
    const message = {
        reply: true,
    };

    provide("reply", message);
};

To address this issue, it is recommended to directly run

provide("reply", message)
from <setup script>

  1. In addition, creating a new constant message within the lambda function that is unrelated to the message prop.

Please refer to the Vue Docs on Components and Provide / Inject for comprehensive information. You can also explore the SFC Playground with an example of Provide / Inject implementation.

For a solution, you can modify your code snippet as follows:

const reply = ref({});
provide("reply", reply);

const replyToMessage = () => {
    reply.value.message = props.message;
    reply.value.reply = true;
};

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

Enable seamless SCSS inclusion in Vue components through automatic importing

My goal is to import a variables.scss file globally in my Vue project. I have set up my vue.config.js file as follows: module.exports = { css: { loaderOptions: { scss: { additionalData: `@import "@/st ...

Is there a way to make a button on a single div only affect that specific div

I have a PHP query that echoes a div for each row in the table. I want the div to slide up and then, when the user clicks the "read more" button, the div slides down. However, since it is echoed in a loop, all the divs have the same IDs and classes. I wo ...

Unlocking the npm package event emitter on the client side in Meteor

Having some trouble with a seemingly basic issue. I came across an NPM package called LOG-WATCHER (used as an example) which keeps an eye on a specific log file on a client's local file system. This package emits events such as 'START', &apo ...

Issue with React hooks: Callback functions from library events (FabricJS) not receiving the updated state values

Why am I not receiving the updated state values within FabricJS events like object:modified, mouse:up, etc... even though I can set state values inside those callback functions. Upon attempting to retrieve the state value, it consistently returns the init ...

The function .load callback was triggered on five separate occasions

I'm currently working with the code below and I have a feeling that I'm overlooking something important but just can't seem to figure it out. Basically, when the user clicks a button, a fragment of the page is loaded. Once this loading is s ...

What are the reasons for validation failure when it is moved into a method?

I am currently in the process of developing a validation function in JavaScript. However, when I extracted the logic into a private method, my validation started failing and I can't seem to figure out why. Here is my HTML definition: <input type= ...

Is there an XML File Wrapper to Generate PDF Output?

Greetings Forum Members, I have been given the responsibility of creating a PDF file from multiple XML files. Has anyone come across an XML wrapper file before? This type of file would essentially contain a list of all the source XML file names in a spec ...

How can data be transferred between web pages using jQuery or JavaScript?

Imagine having two different pages on a Classified car website: The first page is the search page, which displays a list of all cars. Check out a sample search page here The second page is the details page, where you can find specific information about a ...

What is the best way to position a background image so that it covers the entire screen but stops before reaching the bottom?

Having a bit of trouble with background image positioning here - it's simple enough to set a repeating background that starts from a specific point at the top. But what I'm trying to achieve is a black background that starts 100px from the top of ...

Encountered an error when attempting to run npm start due to the absence of the required module 'minizlib

I recently cloned a react-native project from GitHub to start working on it, but encountered an issue with npm start failing and displaying the following error: Error: Cannot find module 'minizlib' Require stack: - /usr/local/lib/node_modules/ex ...

Retrieve information from a PHP file using AJAX when the output is just a single line

I never thought I would find myself in this situation, but here I am, stuck. I just need a single result from this PHP file, so is using an array really necessary? Despite my efforts to console.log(result) multiple times, all I get back is "null". What c ...

Creating a Authentic Screw Top Appearance with CSS

I am striving to create a realistic screw head. Here is what I have done so far: <div class="screw"><div class="indent"></div></div> .screw { position: absolute; top: 10px; left: 49%; width: 30px; height: 30px ...

Determine if an array of objects within React JS contains additional objects

I need assistance in displaying the <div className="songs-list-header-col">Album</div> only if the tracks array contains the artist property as an object. In cases where the artist is not an object, I do not want to display the <di ...

Is my Javascript experiencing a shortage of asyncIds? (Encountered RangeError in inspector_async_hook.js)

One issue that I frequently encounter while using async/await is the following error: RangeError: Value undefined out of range for undefined options property undefined at Set.add (<anonymous>) at AsyncHook.init (internal/inspector_async_hook ...

Assign the ng-repeat item to a variable in the controller's scope

Can anyone help me figure out how to pass a particular item from my view to a function in my controller? Here is the code: The view where I want to pass p.id <tr ng-repeat=" p in projetsListe"> <td>{{p.NomProjet}}</td> <td>{{c ...

Welcome to the JavaScript NodeJs Open Library!

I am trying to open multiple images simultaneously in the default Windows Photo Viewer that I have stored in my folder using the npm open library: let files = ['Dog.gif', 'Cat.jpeg']; for(let i=0; i<files.length; i++){ open(`${file ...

Creating a dropdown menu in Vue 3: A step-by-step guide

I've scoured the entire internet, but I still can't seem to resolve this issue. When using the code below, I keep getting an error message that says 'Uncaught ReferenceError: VueSelect is not defined.' Can you help me figure out what&ap ...

Retrieve the date for the chosen time slot by utilizing the fullCalendar feature

I've been experiencing issues with a piece of code that is supposed to retrieve the date corresponding to a user-selected slot. Here's what I've tried so far: $('.fc-agenda-axis.fc-widget-header').on('mousedown', functio ...

Issue: The GET request to a third-party API using Fetch API encountered a "TypeError: Failed to fetch" error

After conducting extensive research and investing hours into this issue, I am at the point where I need to seek assistance. I am attempting to make a GET call to a third-party Infutor API using the fetch API in my ReactJS Project. Initially, I encountered ...

Challenges encountered when redirecting users with a combination of javascript and php

I have a login form that triggers a JavaScript function upon submission. This function calls a PHP page to process the input. The issue I'm facing is with how the redirections are displayed based on the user's role type. It attempts to display t ...