How to loop through firestore array and fetch values in React Native

Viewed 546

I have an array in my firestore database that holds categories of services. When a user enters the details section I want to display these categories.

My problem is that whenever I enter the details Screen I get an error when I am trying to map the array.

i get an error here :

{details.category.map((category,index)=> (
            <View style={styles.categoryContainer} key={index}>
                <FontAwesome name="tag" size={16} color="#fff" />
                <Text style={styles.category}>{category}</Text>
              </View>
           ))} 

"Render Error: undefined is not an object, evaluating details.category.map"

Even though I get all the correct details if I remove this line of code. What am i doing wrong?

enter image description here

here is my code:

const DetailsScreen = ({route}) => {

  const [details, setDetails] = useState([]); 
  const servID = route.params.serviceID;
  const navTitleView = useRef(null);

  const fetchServicesDetails = async () => {
    try{

     firestore()
      .collection("Services")
      .doc(servID)
      .get() 
      .then((snapshot) => { 
        if (snapshot.exists) { 
          setDetails(snapshot.data()); 
          } else { 
              console.log("doesn't exist");
           } 
        })
    
    }catch(e){
      console.log(e)
    }
  }

  useEffect(()=>{
    fetchServicesDetails();
    },[]);

    

  return (
    <View style={styles.container}>

        <View style={styles.section}>
          <View style={styles.categories}>
           {details.category.map((category,index)=> (
            <View style={styles.categoryContainer} key={index}>
                <FontAwesome name="tag" size={16} color="#fff" />
                <Text style={styles.category}>{category}</Text>
              </View>
           ))}     
            
          </View>
        </View>

        
  
  );
};

export default DetailsScreen;
1 Answers

The problem is your initial state for details is and empty array [] and you are trying to access a property 'category' on an array like details.category which is undefined (it's not a map).

The snapshot.data() object has the data of your whole document. It's a map and not an array. You should set the array of categories in your state.

const [categories, setCategories] = useState([])

//after fetching the data
setCategories(snapshot.data().category)

// Then use a map on this categories object
categories.map((categories, index) => {...})

In case you want that details state as it is, then set your initial state to a map like this:

const [details, setDetails] = useState({category: []})
// now details.category is defined
Related