将获取的数据写入来自 firebase 实时数据库的变量反应

Write fetched data to variable from firebase realtime database react

我正在尝试将获取的数据保存到变量中,但我总是得到“太多的重新呈现”或“未定义”。我做错了什么

import {
  child,
  get,
  getDatabase,
  ref,
} from "firebase/database";

const db = getDatabase();

function App() {
  const [data, setData] = useState();
  const getData = ref(db);

  useEffect(() => {
    const fetch = () => {
      get(child(getData, "tokens/")).then((snapshot) => {
        const fetched = snapshot.val();
        setData(fetched);
      });
      setTimeout(() => {
        console.log(data);
      }, 500);
    };
    fetch();
  }, []);
}

不需要setTimeout()。您可以在 promise resolve 时打印数据,如下所示:

function App() {
  const [data, setData] = useState();
  const getData = ref(db);

  useEffect(() => {
    const fetchData = () => {
      get(child(getData, "tokens/")).then((snapshot) => {
        const fetched = snapshot.val();
        console.log(fetched)
        setData(fetched);
      }); 
    };
    fetchData();
  }, []);
}

我还重命名了 fetch 函数以避免与 Fetch API

混淆