Home > Blockchain >  Firebase - return the value from the onSnapshot event in function
Firebase - return the value from the onSnapshot event in function

Time:03-27

I am trying to return the value from function that has the onSnapshot() event but keep getting this weird error. Basically, I call this action and return the data from it like I would in any other function. But I keep getting this error and I do not know how to fix it.

This is the error

Uncaught TypeError: Cannot add property 0, object is not extensible
    at Array.push (<anonymous>)

This the function

export const getQuestions = () => {
  var questions = [];
  onSnapshot(collection(firebaseDatabase, "questions"), (querySnapshot) => {
    querySnapshot.docs.forEach((doc) => {
      if (doc.data() !== null) {
        questions.push(doc.data());
      }
    });
  });
  return questions;
};

Also this function is used with Redux Thunk and Redux Toolkit.

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getQuestions } from "../../utils/firebase-functions/firebase-functions";

export const getAllQuestions = createAsyncThunk(
  "allQuestions/getAllQuestions",
  async () => {
    const response = getQuestions();
    return response;
  }
);

export const allQuestionsSlice = createSlice({
  name: "allQuestions",
  initialState: {
    allQuestions: [],
    loading: false,
    error: null,
  },
  extraReducers: {
    [getAllQuestions.pending]: (state) => {
      state.loading = true;
      state.error = null;
    },
    [getAllQuestions.fulfilled]: (state, action) => {
      state.allQuestions = action.payload;
      state.loading = false;
      state.error = null;
    },
    [getAllQuestions.rejected]: (state, action) => {
      state.loading = false;
      state.error = action.payload;
    },
  },
});

export default allQuestionsSlice.reducer;

Where it is dispatched

const dispatch = useDispatch();
  const tabContentData = useSelector(
    (state) => state.allQuestions.allQuestions
  );

  useEffect(() => {
    dispatch(getAllQuestions());
  }, [dispatch]);

  console.log(tabContentData);

CodePudding user response:

You can try returning a promise when the data is being fetch for first time as shown below:

let dataFetched = false; 

export const getQuestions = () => {
  return new Promise((resolve, reject) => {
    onSnapshot(collection(firebaseDatabase, "questions"), (querySnapshot) => {
      querySnapshot.docs.forEach((doc) => {
        if (doc.data() !== null) {
          questions.push(doc.data());
        }
      });
 
      if (!dataFetched) {
        // data was fetched first time, return all questions
        const questions = querySnapshot.docs.map(q => ({ id: q.id, ...q.data()}))
        resolve(questions)
        dataFetched = true;
      } else {
        // Questions already fetched,
        // TODO: Update state with updates received
      }
    }); 
  })
};

getQuestions() now returns a Promise so add an await here:

const response = await getQuestions();

For updates received later, you'll have to update them directly in your state.

  • Related