Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign objects to an array

I am querying data from firebase, I then want to assign the fetch data to be an array

This is my code

         let list = [];
        dispatch(fetchUsersPending());
        db.collection("users").get().then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
                list.push({...doc.data()});
                console.log('All Users: ', list);
                dispatch(fetchUsersSuccess(list));
            });
        }).catch((error) => {
            var errorMessage = error.message;
            console.log('Error fetching data', errorMessage);
            dispatch(fetchUsersFailed({ errorMessage }));
          });;

But in my console am getting an error showing Error fetching data Cannot add property 1, object is not extensible in react firebase

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think your current approach also causes to many unnecessary dispatches to the store. With the following solution you only map your array to documents once and then dispatch them all at once.

With async/await

const fetchData = async () => {
    try {
        dispatch(fetchUsersPending());
        const users = (await db.collection('users').get()).docs.map((doc) => ({ ...doc.data()}));
        dispatch(fetchUsersSuccess(users));
    } catch (errorMessage) {
        dispatch(fetchUsersFailed({ errorMessage }));
    }
}

With .then()

const fetchData = () => {
        dispatch(fetchUsersPending());
        const users = db.collection('users').get().then((snapshot) => {
            const users = snapshot.docs.map((doc) => ({ ...doc.data() }));
            dispatch(fetchUsersSuccess(users));
    }).catch((errorMessage) {
        dispatch(fetchUsersFailed({ errorMessage }));
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading