React-Query:数据未定义

React-Query : data is coming out as undefined

我正在尝试从 firebase 获取数据,但数据显示为未定义,状态为成功,但数据似乎无法正常工作。

fetchstory 中的 console.log 似乎获得了所需的数据,但我无法将数据分配给 useQuery。

import { View, Text, FlatList } from "react-native";
import React from "react";

import { collection, getDocs } from "firebase/firestore";
import { db } from "../../lib/Firebase";

import { useQuery } from "react-query";

const fetchstory = () => {
  const storyRef = collection(db, "Stories");
  getDocs(storyRef).then((snapshot) => {
    let stories = [];
    snapshot.docs.forEach((doc) => {
      stories.push({
        title: doc.data().title,
        id: doc.id,
      });
    });
    console.log(stories);
    return stories;
  });
};

const Header = () => {
  const { data, status } = useQuery("story", fetchstory);
  // console.log(data);

  const renderList = ({ item }) => {
    return (
      <View>
        <Text>{item.title}</Text>
      </View>
    );
  };

  return (
    <View>
      <Text>Header</Text>
      <Text>{status}</Text>
      <FlatList
        data={data}
        keyExtractor={(item) => item.id}
        renderItem={renderList}
      />
    </View>
  );
};

export default Header;

尝试在 getDocs() 之前添加一个 return:

const fetchstory = () => {
  const storyRef = collection(db, "Stories");

  // Add return here 
  return getDocs(storyRef).then((snapshot) => {
    let stories = [];
    snapshot.docs.forEach((doc) => {
      stories.push({
        title: doc.data().title,
        id: doc.id,
      });
    }); 
    return stories;
  });
};

或者您可以使用 async-await 语法:

const fetchstory = async () => {
  const storyRef = collection(db, "Stories");
  const snapshot = await getDocs(storyRef);

  return snapshot.docs.map((d) => ({ id: d.id, title: d.data().title }))
}