Managing State with Vuex: Storing Getter Results in the State

I'm encountering an issue with my Vuex.Store:

My goal is to retrieve an object (getter.getRecipe) by using two state entries as search criteria (state.array & state.selected) through a getter. Then, I want to store the outcome in my state (state.recipe) so that I can update it within components (e.g., modifying one key of the recipe object based on user interaction). However, I'm unsure of how to save the result of getters in my state ("this.getters.getRecipe" isn't functioning...). Any suggestions would be greatly appreciated. Thank you.

//store.js (vuex store)

export const store = new Vuex.Store({
state: {
   array: [recipe1, recipe2],
   selected: 0,
   recipe: this.getters.getRecipe()
 },
getters: {
   getRecipe: (state) => {
    return state.array[state.selected]
   }
 }
})

Answer №1

For a more efficient approach, consider utilizing Method style getters with parameters:

You have the ability to pass arguments to getters by returning a function. This comes in handy when you need to access an array within the store:

Here's a simple example:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

To implement this example:

store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

or if used inside a component:

this.$store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

This method ensures that your state maintains its integrity as a pure data structure, adhering to the unidirectional data flow concept presented by the flux pattern.

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

JavaScript - Functions in objects losing reference to previously created object properties

Having trouble with my Candy function. When I create an object of the Candy function, all attributes are created correctly. However, when I try to run the draw function, it always uses the properties of the second object created instead of the one I want. ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...

Converting MySQL data to JSON format in PHP, including handling nested objects

Hey there, I'm currently working on organizing these results into arrays in PHP so that I can convert them into JSON objects and send them over to the client. Here is what the query results look like: id name hours cat status 3bf JFK Int 24 ...

I'm having trouble locating my route for some unknown reason

I've set up a basic code structure to test my routes, but I keep getting a 404 error. Although I have an app.all function to catch errors, I'm having trouble pinpointing where the issue lies. Below is my index.js file, where I've configured ...

Is the behavior of a function with synchronous AJAX (XMLHttpRequest) call in JavaScript (Vanilla, without jQuery) the same as asynchronous?

I'm facing an issue with a file named tst.html and its content: part two (purely for demonstration, no extra markup) The challenge arises when I try to load this file using synchronous AJAX (XMLHttpRequest): function someFunc() { var str = &ap ...

When I utilize $router.push() to navigate to a different page, the back button will take me back to the previous page

Within my Vue project, there is an HTML page that I am working on. Here is the link to the page: https://i.sstatic.net/cbtqM.png Whenever I click on the "+"" button, it redirects me to this specific page: https://i.sstatic.net/0rmMD.png This page funct ...

Is your AngularJS code throwing an error?

$scope.logout = function () { //var auth_token = $cookieStore.get('auth_token'); Auth.delete({ 'auth_token': $cookieStore.get('auth_token') }, function(data){ $scope.isLoggedIn = false; $cookieSto ...

Is there a way to enhance this Java script file reader into a multi-file reader?

I am seeking assistance with JavaScript as it is not my strong suit, but I require it for my website. My goal is to be able to read the files that I select. Below you can find the input form: <form name="filUpload" action="" method="post" enctype="mul ...

Guide to crafting an effective XHR request using AJAX

Here's a snippet of my basic web page: <!DOCTYPE html> <html> <head> </head> <body onload="start()"> </body> </html> Below is the XMLHttpRequest function I've implemented: function start(){ / ...

Construct a string by combining the elements of a multi-dimensional array of children, organized into grouped

My task involves manipulating a complex, deeply nested array of nodes to create a specific query string structure. The desired format for the query string is as follows: (FULL_NAME="x" AND NOT(AGE="30" OR AGE="40" AND (ADDRESS ...

Understanding the getJSON MethodExplaining how

$.getJSON( main_url + "tasks/", { "task":8, "last":lastMsgID } I'm a bit confused about how this code functions. I'm looking for a way to retrieve messages from a shoutbox using a URL or some sort of method that the function here ...

Troubleshooting: Ruby on Rails and Bootstrap dropdown issue

Having some issues with implementing the bootstrap dropdown functionality in my Ruby on Rails application's navigation bar. I have made sure to include all necessary JavaScript files. Below is the code snippet: <div class="dropdown-toggle" d ...

The functionality of a basic each/while loop in jQuery using CoffeeScript is not producing the desired results

I've been experimenting with different methods to tackle this issue. Essentially, I need to update the content of multiple dropdowns in the same way. I wanted to use an each or a while loop to keep the code DRY, but my experience in coffeeScript is li ...

Guide on utilizing exported API endpoint in Node and Express

Seeking a deeper understanding of express and its utilization of various endpoints. Recently came across an example of an endpoint that reads in a json file, demonstrated as follows: const fs = require('fs'); const path = require('path&apos ...

Transforming a menu tab into an active anchor when navigating to a particular section

Hello, I have successfully created a JavaScript code that can dynamically add menu tabs into the menu list window.addEventListener("load", () => { const navList = document.getElementById("nav_list") const fragment ...

Leverage the power of JavaScript validation combined with jQuery

Hello, I'm relatively new to the world of Javascript and jQuery. My goal is to create a suggestion box that opens when a user clicks on a specific button or div element. This box should only be visible to logged-in users. I have some knowledge on how ...

Ways to access dropdown menu without causing header to move using jQuery

Greetings everyone, I am currently working on a dropdown language selection feature for my website. The issue I am facing is that when I click on the language dropdown in the header, it causes the height of the header to shift. $('.language- ...

What is the proper procedure for configuring Babel and executing "npm run dev" in the terminal without encountering the "ERROR in ./src/js/index.js" message?

My goal is to include the babel/polyfill with the index.js files using webpack. After completing the setup, I tried running "npm run dev" in the command prompt but encountered an error. The initial line of the error message said "ERROR in ./src/js/index.js ...

Testing multiple regex patterns using jQuery

I am attempting to run multiple regex tests on an input field. Here is the script: $("#search-registration").keyup(function () { var input_data = $('#search-registration').val(); var regexTest = function() { this.withPrefix = /^ ...

Centering navigation using HTML5

I've been struggling a bit trying to build a website, particularly with centering my <nav> tag. Despite reading numerous suggestions like using CSS properties such as margin: 0 auto; or text-align: center, nothing seems to be working for me. Si ...