user3787954
user3787954

Reputation: 39

Fetching data with redux from firebase

I am trying to fetch from Firebase some data using redux and display them with react within a material table component. The data are received but after the data arrived I receive this error: TypeError: Cannot read property 'length' of undefined. I think that the payload is sent before that all the data to be received from firebase. Still, I am using await on this and I don't understand where I am getting wrong.

export const fetchReviews = () => async (dispatch) => {

const reviewsCollectionRef = db.collection('reviews');
let reviews = [];
 await reviewsCollectionRef .get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
    // doc.data() is never undefined for query doc snapshots
    // console.log(doc.id, " => ", doc.data());
    reviews.push(doc.data());
  
}); }).then(() =>   dispatch({
type: FETCH_DATA_FROM_FIREBASE,
payload: reviews
}));

Upvotes: 0

Views: 247

Answers (1)

Praveen Dass
Praveen Dass

Reputation: 616

Try the below code:

export const fetchReviews = () => async (dispatch) => {
  let reviews = [];
  //perform asynchronous tasks
  await db.collection('reviews').get()
  .then((querySnapshot) => {
    querySnapshot.forEach(function(doc) {
      reviews.push(doc.data());
    })       
  });
  dispatch({
    type: FETCH_DATA_FROM_FIREBASE,
    payload: reviews
  });
}

Upvotes: 1

Related Questions