Issue occurs when trying to access the 'set' property of an undefined variable, leading to an error message stating "Cannot read property 'set' of undefined" while using 'this

I'm facing an issue while setting up basic cookies for my Vue project. When I try to set a cookie, I encounter the following error. My package.json file indicates that I am using vue-cookies version ^1.7.4. The error message occurs when I click the button to create a cookie:

ncaught TypeError: Cannot read property 'set' of undefined
    at Proxy.setCookie (VM6493 Register.vue:45)
    at Object.onClick._cache.<computed>._cache.<computed> (Register.vue?db27:29)
    at callWithErrorHandling (runtime-core.esm-bundler.js?5c40:154)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?5c40:163)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?830f:333)
setCookie @ VM6493 Register.vue:45
Object.onClick._cache.<computed>._cache.<computed> @ Register.vue?db27:29
callWithErrorHandling @ runtime-core.esm-bundler.js?5c40:154
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js?5c40:163
invoker @ runtime-dom.esm-bundler.js?830f:333

The Register.vue file contains the button responsible for setting the cookie:

<template>
  <layout>
    <button v-on:click="setCookie()">Click For Cookie</button>
  </layout>
</template>

<script>
import Layout from "./components/Layout";
import axios from "axios";


export default {
  name: "Home",
  components: {
    Layout,
    vlink
  },
  data: () => {
    return {
      username: "",
    }
  },
  methods: {
    setCookie() {
      this.$cookies.set("username", "bilbobaggins")
    }
  }
}
</script>

<style scoped>

</style>

Upon navigating to the Register.vue page, a warning is displayed:

[Vue warn]: Extraneous non-props attributes (install, config, get, set, remove, isKey, keys) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. 
  at <Layout install=fn<install> config=fn<config> get=fn<get>  ... > 
  at <Home install=fn<install> config=fn<config> get=fn<get>  ... > 
  at <App install=fn<install> config=fn<config> get=fn<get>  ... >

This is how my main.js file looks like:

import {createApp, h} from 'vue'
import App from './App.vue'
import Register from "./Register"
import "./vue-api-call/styles.css"
import VueCookies from 'vue-cookies'


const routes = {'/': App, '/register': Register}
const SimpleRouter = {
  data: () => ({
    currentRoute: window.location.pathname
  }),
  computed: {
    CurrentComponent() {
      return routes[this.currentRoute]
    }
  },
  render() {
    return h(this.CurrentComponent)
  }
}


createApp(SimpleRouter, VueCookies).mount("#app")

I have attempted changing the function in the Register.vue file from 'this' to 'window' or 'VueCookies' and also tried different ways to '.use' the VueCookies module in my main.js file. However, none of these attempts resolved the issue. Any assistance would be greatly appreciated. Thank you!

EDIT: Just experimented with importing Vue-Cookies in the script section of my Register.vue file and modifying the function to

VueCookies.VueCookies.set("username", "bilbobaggins")
. Unfortunately, this resulted in the same error message.

Answer №1

It appears that the vue-cookie package is not compatible with Vue 3 due to the use of the outdated Vue.prototype.$cookie method in the install function, which is now replaced by Vue.config.globalProperties in Vue 3 (https://v3-migration.vuejs.org/breaking-changes/global-api.html#vue-prototype-replaced-by-config-globalproperties). This issue is still unresolved in the GitHub repository for the vue-cookie module: https://github.com/cmp-cc/vue-cookies/issues/59.

If you are using Vue 3, you will need to modify the code within the vue-cookies node module as follows:

install: function (Vue) {
            Vue.prototype ? Vue.prototype.$cookies = this : Vue.config.globalProperties.$cookies = this;
            Vue.cookie = this;
        },

This fix was suggested by LittleWhiteLoti, and credit goes to them: https://github.com/cmp-cc/vue-cookies/issues/59#issuecomment-823796719

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

Issue encountered while attempting to send a direct message to a user that has been mentioned

Attempting to create a reminder command in discord.js with two arguments: the message and the mentioned user to remind but encountering an error. Code snippet: client.on('message', (message) => { const { content, guild, channel, author } = m ...

What could be causing the removal of style classes from my element after it is appended?

Could you please explain how it functions? I am attempting to append a div with content using innerHTML and it is working, but without any of the styling classes being applied. const element = document.createElement("div"); element.classList.add("col ...

Is it possible to generate a basic HTML page using Express JS without utilizing Ejs or any other templating engine

I have a basic HTML file with a Bootstrap form, along with a simple API coded within. In my server.js file, I've specified that when I request /about, it should redirect me to the about.html page. However, instead of redirecting, I'm encountering ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...

Trouble persisting with emailjs even after successful installation

After running the command npm install emailjs-com --save to install email-js in my project, I attempted to import emailjs from "emialjs-com". However, I encountered an error stating that it can't resolve 'emialjs-com' in '/Use ...

The global variable remains unchanged within an ajax request

Here is the code I am working with: In developing this code, I referenced information about the window variable from here <script> $(window).on("load", function() { function myForeverFunc(){ ...

Adding regional dependencies to Lambda deployment

I am working on a project with multiple "micro-services" deployed to AWS Lambda. Along with these services, I also have shared libraries that need to be included in the deployment. Here is how my directory structure looks: /micro-service-1 /dist ...

Tips for inserting HTML into elements using Angular

Recently, I delved into Angular and decided to experiment with Ajax by fetching a document to display on my webpage. The process worked flawlessly, but now I face a new challenge: injecting HTML content into a DOM element dynamically. Typically, this task ...

Duplicate a Google Sheet and save it to a specific folder in Google Drive

I currently have two spreadsheets in my possession. The first spreadsheet consists of raw data that includes unique employee numbers and the names of the employees. The second spreadsheet is the one I aim to duplicate to a designated Google Drive folder. M ...

Is there a way to allow users to edit all the input fields within the td elements when they click the edit button for a specific row?

I am completely new to web dev and I'm struggling with what should be a simple task. My goal is to enable editing of all inputs in a table row when the edit link is clicked. Since I am not using jQuery, I prefer a pure JavaScript solution if possible. ...

Issues arise with the functionality of webcams in conjunction with JavaScript on select devices

I am currently working on developing an Electron application using Vue.js that incorporates a webcam feature. Interestingly, the webcam functions perfectly within the Electron application on one computer but only displays a black screen on another computer ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

Text that fades in and out based on scrolling past a specific point

There's a text containing <p> and <h1>. The text finishes with one <h1>. I'm looking to speed up the Y translation of the <p> twice when I reach the bottom of the document (where the last h1 is located in the middle of th ...

"Experience the power of Vue.js 3 and vue-router as the @click event seamlessly refreshes the entire

Just getting started with Vue and I'm trying to figure out how to toggle the menu open/close on mobile navigation without causing the whole page to reload. Any suggestions on how to prevent that? Here's my code: <router-link to="/ " @click="t ...

"Engaging with the touchscreen inhibits the triggering of click

Within this div, I have implemented touch-action:pan-y;. Surrounding this div is an anchor tag. If you click on the div, the link will successfully redirect. However, if you swipe on the div and then click, the link won't work on the first attempt bu ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...

In the process of attempting to upload a .tsv file through the front end interface, I am encountering a challenge as the file remains stored on my server. What is the

I've got a function set up on my Express server that sends a file dependent on D3.JS. app.get('/dashboard', function(req, res) { var timestamp = utility.timestamp(); console.log('[' + timestamp + '] Request made to rend ...

Guide on uploading multiple files with the integration of CodeIgniter and Vue.js

It seems like when using codeigniter $this->upload->do_upload('file'), all my files are being uploaded at once but they are getting renamed to the same name. For example, if I upload files named 1.png, 2.png, 3.png, 4.png, after the upload, ...

Transferring an Array from PHP to Javascript

I'm attempting to pass a PHP array so that I can use it in JavaScript. The PHP code I have written is shown below: <?php $link = mysqli_connect("localhost", "root", "password", "database"); /* check connection */ if (mysqli_connect_errn ...