Firebase - return 函数中 onSnapshot 事件的值

Firebase - return the value from the onSnapshot event in function

我正在尝试 return 来自具有 onSnapshot() 事件的函数的值,但一直收到这个奇怪的错误。基本上,我像在任何其他函数中一样调用此操作和 return 来自它的数据。但是我一直收到这个错误,我不知道如何解决它。

这是错误

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

这个函数

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

此函数还与 Redux ThunkRedux 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;

发货地

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

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

  console.log(tabContentData);

您可以尝试在第一次获取数据时返回一个承诺,如下所示:

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() 现在 returns 一个 Promise 所以在这里添加一个等待:

const response = await getQuestions();

对于以后收到的更新,您必须直接在您所在的州进行更新。