Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

280
Vistas
Firebase - return the value from the onSnapshot event in function

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);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda