What is the best way to add a key to a JavaScript array while keeping it reactive in Vue.js?

If there's an array in the state:

  state: {
    users: []
  },

Containing objects like:

{
  id: 1,
  name: "some cool name"
}

To add them to the store using a mutator like users.push(user);, how can we ensure that instead of 0:{...}, it uses the actual id as the key 1:{...}?

One approach would be users[user.id] = user, but this might not maintain reactivity in Vue.js.

Answer №1

If you are looking to access data by id, using an array may not be the best choice. Consider using an object instead, like users: {}. Arrays work best when there are minimal gaps between ids.

To ensure reactivity in your values, utilize Vue.set, as outlined in the Vue.js documentation here: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats. For instance:

Vue.set(users, user.id, user)

If you opt to continue using an array, there are alternative methods like https://v2.vuejs.org/v2/guide/list.html#Caveats, such as using splice.

For further information on normalizing data in Vuex, check out this thread: https://forum.vuejs.org/t/vuex-best-practices-for-complex-objects/10143

Update:

Basing on your requirement for key-based lookup and filtering, consider storing values in an object and creating a getter or computed property for Object.values(users) when needing an array format. Getters and computed properties are cached, minimizing overhead when users change. This array can then be filtered using filter.

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

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

The battle between HTML5's async attribute and JS's async property

What sets apart the Html5 async attribute from the JS async property? <script src="http://www.google-analytics.com/ga.js" async> versus (function() { var ga = document.createElement('script'); ga.type = 'text/javascript&apo ...

Can MUI FormControl and TextField automatically validate errors and block submission?

Are MUI components FormControl and TextField responsible for error handling, such as preventing a form from being submitted if a required TextField is empty? It appears that I may need to handle this functionality myself, but I would like some clarificatio ...

Unable to load CSS background image

As I develop a website for a fictional company to enhance my skills in HTML, CSS, and JavaScript, I am encountering an issue with loading my background image. If someone could review my code to identify the problem, I would greatly appreciate it. Check ou ...

Pass Form ID To Function In A Dynamic Way

I have multiple forms on my webpage and I want to use the same ajax function for all of them. It currently works well for one form by fetching the id with getElementById and then passing it to the ajax function. My goal is to dynamically pass down the form ...

Angular.js - organizing a list of items and preserving the outcome

Here is a compilation of randomly arranged items: <ul class="one" drag-drop="page.items"> <li ng-repeat='item in page.items|orderBy:page.random as result'> <img ng-src="http://placecage.com/{{item.id*100}}/{{item.id*100}}"& ...

Troubleshooting: Why is Jquery unable to retrieve image height?

Having trouble using jQuery to find the actual height of the first image nested within a container. I can access the src attribute but not the height. Any suggestions on how to get the accurate height? Is it necessary to retrieve heights via CSS? Unfortu ...

Adding JavaScript in the code behind page of an ASP.NET application using C#

Currently, my challenge involves inserting a javascript code into the code behind page of an asp.net application using c#. While browsing through various resources, I stumbled upon some solutions provided by this website. Despite implementing them as inst ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

What is the impact of a floated element on vertical spacing?

I have come across an article discussing the usage of CSS, but I am puzzled as to why image number four is not positioned below image number one. Instead, it appears below image number three. Can someone please explain this to me? Here is the HTML code sni ...

How should an object be properly passed as a prop using vue router?

In my application, I have a PreviewProduct component that emits a product object to the App.vue file when clicked. My next goal is to pass this product object to the DetailedProduct component using the following method: handleProductClicked(product) { ...

Issue with series of node commands getting stuck on npx command

I have a custom node script that I use to automate the setup of my application. This script creates directories, generates files, and executes a series of node commands. Everything functions correctly for the most part. The specific commands being executed ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

As the user types, the DD/MM/YYYY format will automatically be recognized in the

In my React component, I have an input box meant for entering a date of birth. The requirement is to automatically insert a / after each relevant section, like 30/03/2017 I am looking for something similar to this concept, but for date of birth instead of ...

Establish an angular scope within the DOM element

I am facing a challenge in creating a new Angular scope and attaching it to a DOM element. The situation is complicated by the fact that I am working on modifying a third-party control and cannot simply use a directive. My approach so far has been: ... = ...

Using Vue.js to make an AJAX request to an API that returns a list in JSON format

I am attempting to utilize an AJAX call with the free API located at that returns a list in JSON format. My goal is to display the result on my HTML using Vue.js, but unfortunately, it doesn't seem to work as expected. This is my JavaScript code: va ...

Invoking a plugin method in jQuery within a callback function

Utilizing a boilerplate plugin design, my code structure resembles this: ;(function ( $, window, document, undefined ) { var pluginName = "test", defaults = {}; function test( element, options ) { this.init(); } test.pro ...

Having difficulty loading the JSON configuration file with nconf

I'm currently attempting to utilize nconf for loading a configuration json file following the example provided at: https://www.npmjs.com/package/nconf My objective is to fetch the configuration values from the json file using nconf, however, I am enc ...

Updating variable values using buttons in PHP and Javascript

I've implemented a like/unlike button along with a field displaying the number of likes. The code below uses PHP and HTML to echo the variable that represents the total number of likes: PHP-HTML: <span>likes: <?php echo $row['likes&apo ...

``In JavaScript, the ternary conditional operator is a useful

I am looking to implement the following logic using a JavaScript ternary operation. Do you think it's feasible? condition1 ? console.log("condition1 pass") : condition2 ? console.log("condition2 pass") : console.log("It is different"); ...