Using arrow functions in Vue Pinia getters to access other functions

sample shop

  getters: {
    setNewName: (state) => (string: string) => {
      state.user.username = string;
    },
    updateUser: (state) => {
      setNewName('Tom'); // setNewName is not defined.
    }
  }

Is there a way to access setNewName within an arrow function?

This example only demonstrates how you can access this within regular functions

Answer №1

It was highlighted by Phil that the getters feature should not modify the state in any way. Since Pinia does not support mutations, it is recommended to utilize actions instead.

Furthermore, Arrow functions are designed to lack a reference to this. Therefore, if you need to access any other store methods or variables within the state, it is advisable to create an action using standard JavaScript function syntax, such as:

import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
  state: (): myState => ({
    user: {name: 'myname'},
  }),
  getters: {
    getName: (state: myState) => state.user.name,
  },
  actions: {
    setName(newName: string) {
      this.user.name = newName
    },
  },
})

Subsequently, in any external file where the defined store has already been imported, simply call the action as follows:

import { useUserStore} from '~/stores/user'
const store = useUserStore()
store.setName('Tom')

Please take note that in Pinia actions, it is highly encouraged to consistently employ regular JavaScript function syntax since they are responsible for altering data within your state.

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

When using classList.replace, it should swap out every instance of the class xxx1yyy with xx

I attempted to swap a class and came across this helpful example here: javascript: replace classList that is inside a conditional Unfortunately, my attempt at modification (shown below) did not work. The use of classList.replace should change all instanc ...

Can you tell me if the "dom model" concept belongs to the realm of HTML or JavaScript?

Is the ability to use "document.X" in JavaScript to visit an HTML page and all its tags defined by the HTML protocol or the ECMAScript protocol? Or is it simply a choice made in the implementation of JavaScript, resulting in slight differences in every bro ...

What's the most effective method for updating the title of the date header on MUI Date Picker?

Does anyone know how to customize the title of the Calendar in MUI Date Picker? I want to add a specific string to the display that shows the month and year, like "August 2014." https://i.stack.imgur.com/qgMun.png I've searched the API but couldn&ap ...

Is there any method to determine whether a floated element has been pushed down?

Imagine a dynamic menu with floating elements, each set at a width of 150px. As the menu's width decreases, the elements progressively move to the next row. You are contemplating how to detect when an element has been moved down. One approach could b ...

Sending NodeJS Buffer as form data to Spring Boot in a correct way

I'm facing an issue with my NodeJS application where I am working with an image buffer called qrCode const qrCodeData = Buffer.from(body).toString('base64'); //body received, not sure if base64 is correct f ...

Is it possible to automatically extract HTML code from a webpage using a function, without having to do it manually?

Is there a way to fetch the HTML code of a website after running a particular function? Here's the scenario I'm dealing with: I need to extract the link of a source embedded in an iFrame element that only becomes visible when I execute a specif ...

Leveraging Redux and React to efficiently map state to props, while efficiently managing large volumes of data and efficiently

Utilizing sockets for server listening, the Redux store undergoes continuous updates with a vast amount of data. While updating the store is quick, the process of connecting the state to the component through the redux connect function seems to be slower, ...

The mystery of the unassigned value in $(this).data(value) when using the jQuery click() method

In my Rails 5 application, I am working on creating a dynamic menu that will guide users to different parts of the site based on their location. The idea is that when they click on a specific menu item from the home page, a modal will appear allowing them ...

What is the best method for packaging a React component library?

Currently, I am working on developing a React component library that I aim to distribute via npm to reach a wide audience. In my development process, I utilize webpack and babel for packaging and code processing. However, as a newcomer to webpack, I am uns ...

Problem with object positioning in Three.js when applying rotation matrix

I am attempting to rotate an object named "moon" (which is represented as a sphere) using a matrix instead of the moon.rotation.y property. Here is the code I am using: moon.applyMatrix(new THREE.Matrix4().makeRotationY(Math.PI/100)); The rotation of the ...

Is it possible for Angular.js timer finish event not to trigger data binding correctly?

I've been working on an AngularJS application that functions as a quiz by displaying pictures and prompting users to select the correct answer by clicking a button. The app is designed to store the user's answers in an object. Everything seems t ...

What is the process for creating a dynamic URL, such as example.com/profile/CroatiaGM?

I am in the process of developing a user control panel, and I have encountered some difficulties with creating a dynamic profile link. For instance, how can I achieve something like example.com/profile/CroatiaGM? Given that my website is primarily coded ...

How can I display a PHP variable in JavaScript?

I am having trouble displaying a PHP variable in Javascript; Below is the code I am using: <script type="text/javascript> $(document).ready(function (){ var n=<?php echo json_encode($count)?>; for(var i=0;i<n;i++){ var div ...

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

Exporting a React parent function to a child component

I have a React project where the rendering works fine, but I am facing an issue with calling a function declared in the parent component. Parent import React, { useState, useMemo, useRef, useCallback, useEffect } from "react"; import { AgGridRe ...

The Vue framework has been designated as an external dependency within the single-spa configuration, but an issue has arisen

Currently utilizing Vue with single-spa, I have embarked on a mission to minimize the bundle size. In pursuit of this goal, my initial approach involved configuring Vue as an external dependency in the webpack.config.js file for each Micro Front-end: exte ...

Experiencing a missing handlebars helper error when utilizing a helper within partials in express-handlebars

I have set up custom helpers using express-handlebars like this: const { create } = require("express-handlebars"); // Configuring the handlebars engine const hbs = create({ helpers: require("./config/handlebars-helpers"), }); app.engi ...

How to Handle an Expired Access Token in VueJS Laravel Passport?

My Vuejs SPA is connected to a Laravel API backend. After successfully obtaining the personal access token, I store it in both localStorage and Vuex state as shown below: token: localStorage.getItem('token') || '', expiresAt: localStor ...

How can radios be made reusable in Vue.js?

Recently started delving into vue.js and encountered an issue where radio values were being repeated in the v-for div. Any ideas on how to resolve this problem? Check out this JSFiddle for reference. <script src="https://unpkg.com/<a href="/cdn-cgi ...

Missing Component when Nested within Route in React Router v6

While incorporating the ChoosePlayer component within a Route using React Router v6, <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/players"> <Route element ...