Search code examples
javascriptfirebasesortingvue.jsvuex

Not able to sort object array in vuex action Vue.js


I am trying sort an array, but somehow sort is not running only proved by console log. I am not able to understand why this is not running. if i run same code in simple javascript runs fine. It would be a great help if someone knows whats happening.

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);
},

enter image description here


enter image description here


Solution

  • You should un the sort inside the onSnapshot callback since your current code is executed in asynchronous way :

     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);
        })