Home > Blockchain >  Flatlist not rendering the code in react native expo
Flatlist not rendering the code in react native expo

Time:08-10

My Code

import {
  StyleSheet,
  Text,
  View,
  Button,
  Image,
  FlatList,
} from "react-native";
import { initializeApp } from "firebase/app";
import { getDatabase, ref, onValue, child, get } from "firebase/database";
import React, { useState } from "react";

const Product = () => {
  //Initialize Firebase
  const firebaseConfig = {
//private
  };
  initializeApp(firebaseConfig);
  const db = getDatabase();
  //Make a variable to store data
  var data = [];
  const dbRef = ref(db, "/Products");
  var indexOfData = 0;
  onValue(
    dbRef,
    (snapshot) => {
      snapshot.forEach((childSnapshot) => {
        indexOfData  ;
        const childKey = childSnapshot.key;
        const childData = childSnapshot.val();
        data.push({
          ["id"]: indexOfData,
          ["key"]: childKey,
          ["value"]: childData,
        });
      });
    },
    {
      onlyOnce: true,
    }
  );
  const [product, setProduct] = useState(data);
  console.log(product);
  const navigateToAnotherPlace = (wheretonavigate) => {
    console.log("Navigating to another place");
    console.log(wheretonavigate);
  };

  const courseCard = ({item}) => {
    return (
      <View style={styles.card}>
        <View style={styles.cardImageCenter}>
          <Image
            style={styles.cardImage}
            source={{
              uri: item.value,
            }}
          />
        </View>
        <Text style={styles.cardHeading}>{item.key}</Text>
        <Button style={styles.cardButton} onPress={navigateToAnotherPlace(item.key)} title="View" />
      </View>
    );
  };
  return (
    <View style={styles.container}>
      <Text style={styles.text}>Product</Text>
        <FlatList
          data={product}
          renderItem={courseCard}
          keyExtractor={(item) => item.id}
        />
    </View>
  );
};

const styles = StyleSheet.create({
  card: {
    backgroundColor: "#fff",
    borderRadius: 5,
    padding: 10,
    margin: 10,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
    height: 300,
  },
  cardText: {
    fontSize: 20,
    fontWeight: "bold",
    margin: 5,
  },
  cardImage: {
    width: "100%",
    height: "100%",
    resizeMode: "contain",
  },
  cardHeading: {
    fontSize: 20,
    fontWeight: "bold",
    margin: 5,
  },
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  cardButton: {
    fontSize: 20,
    backgroundColor: "#f2f2f2",
    borderRadius: 5,
    padding: 10,
    margin: 10,
    shadowColor: "#000000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
    height: 300,
    width: "100%",
    alignItems: "center",
  },
  cardImageCenter: {
    alignItems: "center",
    justifyContent: "center",
    height: "70%",
    width: "100%",
  },
});

export default Product;

Here I can get the object from firebase but can't render it with flatlist please add answers When I test this app everything works fine but the flatlist does not show the data if you have any answer please send the whole code So what is the purpose of this screen? Ans-> I am getting data from firebase and I need to display that database in form of cards

CodePudding user response:

I have tried to refactor your code , added the state where you are storing the array data and using the product globally in your component.

I have passed the product as an argument in your flatlist function render. please try and let me know the result.

const Product = () => {
  const [product, setProduct] = React.useState([]);
  //Initialize Firebase
  const firebaseConfig = {
     //private
  };

  React.useEffect(() => {
    initializeApp(firebaseConfig);
    const db = getDatabase();
    //Make a variable to store data
    var data = [];
    const dbRef = ref(db, "/Products");
    var indexOfData = 0;
    onValue(
      dbRef,
      (snapshot) => {
         snapshot.forEach((childSnapshot) => {
           indexOfData  ;
           const childKey = childSnapshot.key;
           const childData = childSnapshot.val();
           data.push({
              ["id"]: indexOfData,
              ["key"]: childKey,
              ["value"]: childData,
           });
        });
      },
      {
        onlyOnce: true,
      }
    );
     setProduct([...product, ...data])

   },[]);

   const navigateToAnotherPlace = (wheretonavigate) => {
      console.log("Navigating to another place");
      console.log(wheretonavigate);
   };

  const courseCard = (item) => {
    return (
      <View style={styles.card}>
        <View style={styles.cardImageCenter}>
        <Image
           style={styles.cardImage}
           source={{
           uri: item.value,
           }}
         />
        </View>
        <Text style={styles.cardHeading}>{item.key}</Text>
        <Button style={styles.cardButton} onPress= 
            {navigateToAnotherPlace(item.key)} title="View" />
     </View>
   );
  };
  return (
     <View style={styles.container}>
       <Text style={styles.text}>Product</Text>
         <FlatList
           data={product}
           renderItem={(product)=>courseCard(product)}
           keyExtractor={(item) => item.id}
         />
     </View>
   );
 };

CodePudding user response:

the UI and FlatList work fine for me. I think the problem in the way that you are fetching the data. Try this:

const Product = () => {
   const [products, setProducts] = useState([]);
   //Initialize Firebase
   const firebaseConfig = {
      //private
   };

  useEffect(() => {
    initializeApp(firebaseConfig);
    const db = getDatabase();
    //Make a variable to store data
    let data = [];
    const dbRef = ref(db, "/Products");
    var indexOfData = 0;
    onValue(
      dbRef,
      (snapshot) => {
         snapshot.forEach((childSnapshot) => {
           indexOfData  ;
           const childKey = childSnapshot.key;
           const childData = childSnapshot.val();
           data.push({
              ["id"]: indexOfData,
              ["key"]: childKey,
              ["value"]: childData,
           });
        });
      },
      {
        onlyOnce: true,
      }
    );
     setProducts(prv=>[...prv, ...data])
   
   },[]);
   /*.....*/

  • Related