fetching and saving firestore data in redux

71 Views Asked by At

I am attempting to update my store with an asynchronous redux action. The initial database query collects the contact docs needed to make the second query for the nested notes due to shallow query limitations.
I am pushing the notes to notesArray, with a final push to contacts to include the contacts data/id and the notesArray.
I am receiving an error:

non extensible object

This error does not persist when removing the notes query, and the contacts load fine without the note data...
Also, I can overcome the error if I copy the contacts array using something like copyContacts = contacts, but for whatever reason it's not available outside the scope of the function. How can I fix this?

export const fetchContactData = () => {
    return async dispatch => {
        try {

            let contacts = [];

            await getDocs(collection(db, 'contacts')).then((docs) => {

                docs.forEach(async doc => {

                    const notesArray = [];

                    //this query is messing it up! This is causing the contacts array to be empty...
                    await getDocs(collection(db, 'contacts', doc.id, 'notes')).then((notes) => {
                        notes.forEach(note => {
                            notesArray.push({ ...note.data(), id: note.id })
                        })
                    })

                    contacts.push({...doc.data(), id: doc.id, notes: notesArray})
                })

            });

            dispatch(contactActions.replaceContactData({
                contacts: contacts || []
            }));

        } catch (error) {
            console.log(error)
            dispatch(
                uiActions.showNotification({
                    status: 'error',
                    title: 'Error',
                    message: 'Error loading contacts.'
                })
            );
        };
    };
};
1

There are 1 best solutions below

0
joshua crowe On

Javascript's forEach loop was not designed for asynchronous code, a for...of loop was the solution.