0

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
}));
1
  • I tired the code of @Praveen Dass 's answer and it works as expected for me. Maybe the issue is that your component is accessing the data when it still hasn't been fetched. Could you share the code that calls the fetchReviews() method? Commented Jul 21, 2020 at 13:12

1 Answer 1

1

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
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

I receive the error before the actual rendering within the component. The error is triggered when the logger is trying to log the payload.
Same result unfortunetly.
The issue was caused by a mistake made by me while I was trying to connect the component to the redux store. Thank you for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.