Zavier Barker
Zavier Barker

Reputation: 57

How to display data from a firebase firestore in React Native

For the Life of me, I cannot get this to render the data that I pull from the database.

Here is the code

function assetList(){
  const [assetL, setAssetL] = useState([]);
  const [errors, setErrors] = useState("");

  const getAssets = async () =>{
    try{
      const list = [];
      console.log("Break");
      db.collection("assets").get().then(function(querySnapshot){
        querySnapshot.forEach(function(doc){
            list.push(doc.data());
        });
      });
      //problem
      setAssetL([...list]);
      //problem
      console.log("list");
      console.log(list);
      console.log("AssetL");
      console.log
    } catch (e) {
      setErrors("Failed To Load Data");
    }
  };
   useEffect(() => {
     getAssets();
   }, []);
   console.log(assetL);

  return(
    <SafeAreaView style = {styles.Heading}>
      <View style = {styles.Heading}>
        <Text style = {styles.headText}>Asset List</Text>
      </View>
        <FlatList
        data = {assetL}
        renderItem={({item}) => <Text>{item.default}</Text>}
        />
    </SafeAreaView>
  );

}

I have narrowed down to at least the most pressing issue, other than my jank way of throwing this page of the app together, is that the setAssetL isnt actually setting the assetL const. Can anyone explain why this is happening and how to fix it?

Upvotes: 0

Views: 376

Answers (1)

Maksym Bezruchko
Maksym Bezruchko

Reputation: 1258

For the getAssets function do something like this:

const getAssets = async () =>{
   try {
      const list = [];
      console.log("Break");
      db.collection("assets").get().then(function(querySnapshot){
         querySnapshot.forEach(function(doc){
            list.push(doc.data());
         });
         setAssetL(list);
      });
      ...
   } catch (e) {
      setErrors("Failed To Load Data");
   }
};

Your code did not work because db.collection("assets").get() function returns a promise and you handle it asynchronously while expecting it to be synchronous.

Here you can read more about async functions

Upvotes: 1

Related Questions