Home > front end >  How to assign objects to an array
How to assign objects to an array

Time:08-02

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

CodePudding user response:

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