Estoy tratando de devolver el valor de la función que tiene el evento onSnapshot() pero sigo recibiendo este extraño error. Básicamente, llamo a esta acción y devuelvo los datos como lo haría en cualquier otra función. Pero me sigue saliendo este error y no se como solucionarlo.
este es el error
Uncaught TypeError: Cannot add property 0, object is not extensible at Array.push (<anonymous>)Esta es la funcion
export const getQuestions = () => { var questions = []; onSnapshot(collection(firebaseDatabase, "questions"), (querySnapshot) => { querySnapshot.docs.forEach((doc) => { if (doc.data() !== null) { questions.push(doc.data()); } }); }); return questions; }; También esta función se usa con Redux Thunk y 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;donde se despacha
const dispatch = useDispatch(); const tabContentData = useSelector( (state) => state.allQuestions.allQuestions ); useEffect(() => { dispatch(getAllQuestions()); }, [dispatch]); console.log(tabContentData);Puede intentar devolver una promesa cuando los datos se obtienen por primera vez, como se muestra a continuación:
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() ahora devuelve una Promesa, así que agregue una espera aquí:
const response = await getQuestions();Para las actualizaciones recibidas más tarde, deberá actualizarlas directamente en su estado.