Pinia accessing data from one getter to another

I manage a shop in Pinia (using Vue 3) that frequently utilizes getters referring to other getters. I've been using state.getterName for this purpose, which has been functioning well, although occasionally it warns me that the getter does not exist. I just realized from the documentation that I should use this. when referencing a getter within another getter.

This is my current approach:

const useMyStore = defineStore('myStore', {
    state:() =>({
        state1: 100
    }),
    getters: {
        getterName1: (state) => {
           return state.state1 * 100
        },
        getterName2: (state) => {
           return state.getterName1 - 100
        }
    }
})

I believe I should be doing it like this:

const useMyStore = defineStore('myStore', {
    state:() =>({
        state1: 100
    }),
    getters: {
        getterName1: (state) => {
           return state.state1 * 100
        },
        getterName2: () => {
           return this.getterName1 - 100
        }
    }
})

My query is: why does using state.getterName incorrectly actually work? What potential risks am I exposing myself to by not using this? Should I consider reorganizing my store to incorporate this?

Including this discussion here for additional context. Also, I want to mention that I do not use TypeScript, so enforcing the return type is not an option.

Answer №1

If you're looking for an alternative, Vue 3 is a great option with Composition API. It's faster, more intuitive, and easier to understand. I've been using it without any conflicts, and my application is scaling gradually.

import { defineStore } from 'pinia'
import { ref } from 'vue

export const useMyStore = defineStore('myStore',() => {
const state1 = ref(100);

const getterName1 = () => state1.value * 100
const getterName2 = () => state1.value - 100

return {state1,getterName1, getterName2}
})

You can now utilize it in any component like this:

import {useMyStore} from 'yourpath/'
const useStore = useMyStore

const test = () => {
useStore.getterName1()
}

<template>
<p>{{useStore.state1}}</p>
</template>

I hope this is helpful for you!

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

Display a text message from the backend code to open a fresh page or pop-up window

Imagine a situation where there is a string variable in the code behind that holds HTML content like this: Dim htmlString As String = "<h3>hello</h3><p>some paragraph</p><table><tr><td>some table content</td> ...

Utilizing Mysql Joins with parameterized queries in Node.js: A Comprehensive Guide

Currently, I am utilizing Node.js and Express.js for my project. In particular, I am incorporating the "mysql2 library" into my development process. My current task involves concatenating and joining queries with parameters in a secure manner. How can I ...

Is there an easy method for extracting URL parameters in AngularJS?

Hello, I'm new to Angular and coming from a background in PHP and ASP. In those languages, we typically read parameters like this: <html> <head> <script type="text/javascript"> var foo = <?php echo $_GET['foo&apo ...

Which is the most efficient method for incorporating Vue.js into Laravel projects: Inertia.js or Laravel UI?

I'm currently knee-deep in a Laravel project and now I'm onto the Vue.js integration part. After doing some research, I've discovered that there are multiple ways to bring Vue into a Laravel project, with Inertia.js and Laravel UI being the ...

The dialogue within the map function is not functioning properly

In my state, I have saved data (objects) known as workitems. When these objects are mapped out to a table, everything functions correctly. However, upon trying to implement a Dialog feature with a button that allows users to view more information about a s ...

Creating a high-performing JavaScript script using AJAX: Tips and Tricks

When it comes to structuring my JavaScript scripts, I often find myself following a similar pattern when dealing with AJAX or server responses. However, I don't believe this is the most efficient method. Is there a better approach for handling these t ...

Tips for maintaining the functionality of IFrame?

I am encountering an issue with tracking clicks on a div that contains an IFrame. While the tracking functionality works, it seems to interfere with the IFrame's functionality. Is there a way to resolve this and make both functionalities work simultan ...

Every time I attempt to load the table, I encounter an error

Encountering errors when attempting to load the table: 'Uncaught ReferenceError: usersArray is not defined at loadUsers (trgames.js:20:17) at trgames.js:22:1' and 'Uncaught TypeError: Cannot set properties of null (setting ...

Is JavaScript responsible for creating threads for non-blocking AJAX requests?

It is widely believed that JavaScript operates on a single-threaded model, but it has the ability to run asynchronously. One intriguing aspect is how this single-threaded model manages non-blocking AJAX requests. Consider a scenario where a non-blocking A ...

AngularJS dropdown menu for input selection binding

Hey there, I need some help with the code below: <input type="text" class="form-controlb" ng-model="item.name" id="name" placeholder="Enter Name" /> Also, I have a dropdown as shown here: <div class="col-sm-12" ng-model="query"& ...

Limiting multiple checkbox inputs in a React application can be easily achieved by utilizing React

Trying to create a form where the user can only check three boxes and uncheck them. The decrement on setCurrentData(currentData - 1) is not working as expected. Even after deselecting, the currentData remains at 3, preventing the user from checking any mo ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: https://i.sst ...

Is it possible to send emails from a local server to Gmail, Yahoo, or Rediff?

Currently, I am developing a feature that allows users to send emails to any recipient including Yahoo and Gmail. Below is the code snippet for my contact form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 ...

Return all HTML code from the Ajax element

I can't seem to pinpoint the issue with my code. When I make an ajax call using the code below: ajax.js: function ajaxObj(meth, url){ var x = new XMLHttpRequest(); x.open(meth, url, true); x.setRequestHeader("Content-type", "application/x-www_form-u ...

Tips for organizing your JSON Structure within ReactJs

In the given example, I have a JSON structure with information about different airlines. The Airline Name is dynamic and we need to separate the JSON into an expected array format. const arr = [ { Airline: "Goair", Departure: "01:50" ...

Issue with React.useEffect not functioning in Express application

I'm having trouble with the state not updating or re-rendering in my code. I've tried logging from inside the useEffect function but nothing seems to happen. Any suggestions on how to make the useEffect work properly? app.js var createError = re ...

Skrollr triggers a fade-in effect once the user reaches a specific distance from the bottom of the

Using skrollr, I have a div positioned at the bottom of some content that I want to fade in once the screen reaches its level. I attempted various examples found on their cheat sheet but had no success. This div is situated above the footer (500px from t ...

When the window is resized, Div escapes from view

My issue is that whenever I resize the browser, the div moves out of the window. I am using the jQuery scroll to plugin for navigating through divs. Oddly enough, when I resize the #home div, everything seems to work fine. However, when I resize other divs ...

Can you explain what purpose does ._[0] serve in args._[0]?

While delving into some Node.js code for creating a small CLI tool, I encountered this underscore notation that seems quite unfamiliar to me. By experimenting with different command line arguments, I've deduced that it essentially involves extracting ...

Eliminating undesirable data coupling in Vue.js

In my application, I have an edit form where a HTTP request is made when the component is created and the response data is saved in two different variables. axios.get(this.initializeURL) .then((res) => { this.form = res.data.form th ...