Having trouble figuring out how to sort an object array within a Vuex action in Vue.js

Currently attempting to sort an array, however, the sorting function doesn't seem to be working as expected based on the console log output. I'm puzzled as to why it's not executing properly. Interestingly, the same code runs fine in simple JavaScript. Any insight into what might be going wrong would be greatly appreciated.

fetchContacts({
    commit
}, userId) {
    let contactsArr = [];
    console.log('contact action triggered');
    db.collection("users").doc(userId).collection("contacts").onSnapshot((snapshot) => {
        snapshot.forEach((el) => {
            contactsArr.push({
                name: el.data().name,
                phone: el.data().phone,
                email: el.data().email,
                id: el.id
            });
        })
    })
    console.log('contact array: '+ contactsArr);
    console.log(contactsArr);
    contactsArr.sort((a, b) => {
        console.log('sorting in ');
        const n1 = a.name.toLowerCase();
        console.log(n1);
        const n2 = b.name.toLowerCase();
        console.log(n2);
        if (n1 > n2) {
            return 1;
        } else if (n2 > n1) {
            return -1;
        } else {
            return 0;
        }
    });
    commit('setContacts', contactsArr);
},

https://i.sstatic.net/ybIGv.png


https://i.sstatic.net/cfpRU.png

Answer №1

In order to ensure proper execution of your code, it is recommended to run the sorting process inside the onSnapshot callback due to its asynchronous nature :

 let contactsArr = [];
    console.log('contact action triggered');
    db.collection("users").doc(userId).collection("contacts").onSnapshot((snapshot) => {
        snapshot.forEach((el) => {
            contactsArr.push({
                name: el.data().name,
                phone: el.data().phone,
                email: el.data().email,
                id: el.id
            });
        })

      console.log('contact array: '+ contactsArr);
    console.log(contactsArr);
    contactsArr.sort((a, b) => {
        console.log('sorting in ');
        const n1 = a.name.toLowerCase();
        console.log(n1);
        const n2 = b.name.toLowerCase();
        console.log(n2);
        if (n1 > n2) {
            return 1;
        } else if (n2 > n1) {
            return -1;
        } else {
            return 0;
        }
    });
    commit('setContacts', contactsArr);
    })
   

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

What is the approach for for loops to handle non-iterable streams in JavaScript?

In the realm of node programming, we have the ability to generate a read stream for a file by utilizing createReadStream. Following this, we can leverage readline.createInterface to create a new stream that emits data line by line. const fileStream = fs.cr ...

Retrieve and showcase PHP results utilizing the power of jQuery/AJAX

I am working with a Leaflet map and a text input field. My goal is to extract the address from the text input, process it using a PHP script, and receive the results back via jQuery. Below is the form structure: <form id="mapcheck" method="POS ...

Fill the next Thursday with JavaScript

I'm having trouble updating the date for the upcoming Thursday using JavaScript. The current script works fine until the end of the month, but if it's the 25th of August, the output will be "Next Thursday - 8/32/2022". I need a more intelligent s ...

Implementing dynamic component rendering and iterating through a list in React JS based on state changes

Trying out React JS for the first time and encountering a couple of issues. 1) Attempting to display a table from a different class upon clicking the show button. However, even when the state is true for showing the table, it doesn't appear. 2) In t ...

Steps to turn off carousel feature in v-tabs

I'm currently working on a horizontal navigation bar using the v-tabs and v-tabs-items components to switch between slides by clicking on a specific tab. However, I have encountered an issue where Vuetify automatically adds a carousel to the v-tabs c ...

Locating the right selector for adding a div to its parent element in jQuery

I have come across an interesting HTML structure: <div class="dropdownedit"> <div class="dropbtn">textxyz</div> <div class="dropdown-content" style="display: none;"> <div href="#" class="ocond" id="text1">text1</div> &l ...

Having an issue with my JavaScript burger menu not functioning properly

I'm really struggling to figure out why my code isn't working. I've checked and rechecked all the links, and everything seems correct. Could it possibly be because the code is outdated? I've been stuck on this for two days now and can&a ...

Troubleshooting: React Native and OneSignal notifications not showing up

Currently, I am developing an app in React Native and working on integrating notifications with OneSignal. Although I am able to efficiently receive notifications, I do not want them to be displayed on the screen when they are received. I came across a ` ...

Combining Socket.io with AJAX for real-time web applications

I am currently working on a web application that relies on Socket.io for delivering notifications to users. I'm wondering if it would be more beneficial to utilize Socket.io exclusively for all client-server communication, or if mixing in traditional ...

Here's a helpful guide on verifying the presence of a value within an array in Quasar

const myproducts = ref([]) const items = ref([ { id: 1, item: 'Vaporub 50Gm' , barcode: '123456'}, { id: 2, item: 'Herbal Cool Oil (300+100)Ml', barcode: '123456' }, { id: 3, item: 'live Oil Bp 70M ...

Using jQuery to select the child element of the parent that came before

Recently, I've been experimenting with creating animations using CSS and jQuery. While it has been successful so far, I'm now looking to take it a step further. Specifically, I want information to appear on top of an image when the user clicks on ...

What is the best way to access a specific element within a component from a different component?

Seeking assistance with communication issues between React components. I have a Container component containing child components Contact, More, and About for a single-page website. Each child component has a reference set. The problem arises when trying to ...

I'm looking for a streamlined method to simultaneously access multiple APIs with GraphQL and React

For my client side project, I'm using GraphQL and React but opting not to use Redux for state management. Instead, I have organized my API calls into custom hook files as shown below: const [getSomeData, { data: getSomeDataData, loading: getSomeData ...

Tips for preserving line breaks when sending a message through the mail

Hi, I'm currently facing an issue: I am trying to send text from a textarea using POST to a PHP script that will write it to a file and display it on the website. However, when I do this, the line breaks disappear and the displayed text ends up lookin ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

ajax receives an empty responseText after sending intermediate data to Python on the backend

Initially, the frontend passed an identification to the backend. The backend utilized this identification to retrieve data from the database. The extracted data then underwent additional processing on the backend before being sent back to the frontend. Be ...

Dealing with TypeScript and the Mongoose loadClass problem

Working with Mongoose's class schemas has been very beneficial for me. Incorporating TypeScript into my Node project has enhanced the development process. I made sure to refer to Mongoose the Typescript way...? in order to ensure that my Model align ...

I am having trouble getting Form.Select to work in my basic react-bootstrap application, despite following the guidelines provided in the react-bootstrap documentation. Can

I am new to utilizing "react-bootstrap with hooks" and currently in the process of creating a basic form. I have been following the guidance provided by react-bootstrap documentation, but I encountered an issue specifically with select/option form elements ...

Implementing AngularJS to Display Images (IMG, PNG, or SVG) Within Dropdown Options

Looking to include an image in an Angular select option list. I've seen examples using data-image within the options, but can't seem to get it working. Any help would be appreciated. Check out the jsfiddle here: http://jsfiddle.net/drt6y0wf/ Is ...

Executing iterations within the document.ready function using jQuery and d3.js

Here is how my data is structured: var IDData = JSON.stringify([["node/105173", "node/38180995", "Agent", "Customer", "1379644.0", 1, 264.0, "1374903"]...] Each row in the data follows the same format, although the length of the array arrays can vary. I ...