How do you write functions in ES6?

When attempting to access my namespaced store in Vue, I encountered an issue:

methods: {
    ...mapActions('Modal', [
        'toggleActive',
    ]),
    close: () => {
        this.toggleActive();
    }

This resulted in the following error message:

Uncaught TypeError: Cannot read property 'toggleActive' of undefined

However, when I made a slight adjustment like so:

close: function() {
    this.toggleActive();
}

I was able to resolve the issue. How can I effectively implement ES6 function syntax with vue/vuex?

Answer №1

When using arrow functions, they will close over the this in the context of where they're defined, instead of having it set when called like regular function functions do. For example:

// `this` refers to the current context here
var o = {
    foo: () => {
        // ...will also refer to the same context as above when `foo` is called
    }
};

To avoid this behavior, it's recommended to use method syntax instead:

methods: {
    // Using a simple method for toggleActive for clarity; if you're transpiling with a tool that understands rest notation for objects, your `mapActions` should be fine *assuming* the functions it creates are not arrow functions
    toggleActive() {
        // ...
    },
    close() {
        this.toggleActive();
    }
};

Keep in mind that this approach is subject to the usual challenges related to the this keyword, which you can read about in detail in the answers provided in this question on Stack Overflow: described in this question's answers.

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

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

Is it possible to run an existing NextJS app with API routes on a mobile platform using either Capacitor or Expo?

I have an established NextJS application that heavily relies on Next's API routes. My goal is to transition the current codebase to function in a mobile environment. I've experimented with Capacitor and attempted to export it as a static site, bu ...

Version 1.0 and higher of Ionic do not display the side menu when using tabs

I have developed an app using Ionic that includes a side menu with tabs feature. The side menu displays correctly when using Ionic version 0.9.27, but it does not show up when the version is 1.0 or higher. What could be causing this issue? HTML Layout & ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

An error occurred with redirecting using jQuery Mobile's new method in version 1.5

Utilizing jQuery Mobile for its history state feature, I am looking to redirect users to another "page" using the jQuery method recommended in their latest documentation. p/s: I prefer the jQuery navigation method due to the hashchange/history support and ...

Saving Information from Various MongoDB Searches on Node.js

Okay, I believe it would be more helpful if I provide my entire node.js route for you to better understand what I am trying to explain. The issue I am facing is with making multiple queries to my MongoDB database (one for each day). The queries are execut ...

The websocket connection established with apollo-server is somehow producing nonsensical output for the connection params

onConnect should receive the connectionParams supplied by the client and then validate that the token has not expired by checking the token property on the connectionParams object. On the client-side, I send these parameters in the following manner: const ...

Leverage Vue Store within a service worker

In my project structure, I have the file service-worker-push.js located in the public folder and registerServiceWorker.js located in the src folder. When a push notification is clicked, I am trying to save that data in the vue store. However, I encountered ...

Transmit information to the Express server

Having difficulty transmitting data to the Backend. I am trying to send the data f1 to QueryBackend.js. However, when I attempt to use console.log(req.body.f1), it always returns as undefined, even though I can retrieve the value in Services.js. Toolbar.j ...

How to address hover problems in D3.js when dealing with Path elements and updating tooltip information after brushing the focus

Seeking assistance with a Multi Series, Focus + Context D3 chart and hoping to address my main queries all at once. The questions that need resolving are: How can I prevent the tooltips I've generated from being affected by the hair-line (which t ...

What's the alternative now that Observable `of` is no longer supported?

I have a situation where I possess an access token, and if it is present, then I will return it as an observable of type string: if (this.accessToken){ return of(this.accessToken); } However, I recently realized that the of method has been deprecated w ...

Does Internet Explorer 10 support the FormData object?

I've developed a JavaScript app that enables me to upload images asynchronously, and it works seamlessly in most browsers. However, the infamous Internet Explorer is causing some trouble... To address this issue, I devised a workaround for IE9- versi ...

Angular’s ng-repeat function is behaving erratically as objects are displayed in the console

Having trouble with my ng-repeat not displaying content. Here is the code for my app.js, client controller, factory, and server controller. Everything else seems to be working fine. I can see all the console logs in Chrome and terminal, but the ng-repeat ...

The JavaScript code does not call an external function to retrieve data from the database

I'm currently facing an issue with retrieving the same version data from my MySQL (MariaDB) Server. In order to streamline the process and improve maintenance, I decided to create a single connection Object to manage all database queries. However, I&a ...

Display issue with ThreeJS cube

Currently, I'm delving into the world of ThreeJS and decided to incorporate the library into my existing NextJS project. My goal was simple - to display a cube on the front page. However, despite my best efforts, nothing seems to be appearing on the s ...

What is the best way to refine the results from an AJAX request in Datatables?

I have successfully configured a Datatables plugin, set up a new table, and populated it with content using an AJAX call: var table= $("#mytable").DataTable({ ajax: "list.json", columns: [ {"data": "name"}, {"data": "location"}, ...

The set method of useState is not causing the specific component to render

My concern arises when trying to update the TaskDetail component located at Right Side. Despite changing the value of the card within the handleCardClick callback, the specific component does not reflect this change. In the provided gif, it can be observed ...

It is impossible to add a new element between two existing elements that share the same parent

I'm attempting to place an <hr> tag between the first and second .field-container. Because they have the same parent, I thought using element1.parentNode.insertBefore(element2, ...) would be the solution. However, it is not working as expected a ...

Can someone advise me on how to ensure my function effectively delivers a desired outcome?

My goal is to learn Javascript on my own, but I'm struggling to make progress. I've created a function called fixedSpending() that takes two inputs, num1 and num2, and adds them together. However, when the user hits the "=" button, I expect the f ...

Angular 2 System.config map leading to a 404 error message

I am encountering a 404 error in the browser console while attempting to map the Auth0 module from node_modules in my Angular 2 project using the system.config in the index file. Index File <!-- 2. Configure SystemJS --> <script> System.con ...