Home > other >  React-Query : data is coming out as undefined
React-Query : data is coming out as undefined

Time:03-21

I am trying to fetch data from firebase but data is shown as undefined, status is successful but data seems not working.

the console.log in fetchstory seems to getting the desired data but I am unable to assign the data to 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;

CodePudding user response:

Try adding a return before getDocs():

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;
  });
};

Alternatively you can use async-await syntax:

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 }))
}
  • Related