skip to Main Content

I’m getting this error when I try to run this code. I have set the products variable as well. Can I know why this error occurs?

<View style={styles.prodCont}>
  <ScrollView horizontal={true} style={{ width: "100%" }}>
    <FlatList
      data={products}
      renderItem={({prod}) => (
        <ProductCard 
          cardType="social"
          title={prod.title}
          imageUrl={prod.imageUrl}
          price={prod.price}
          unit={prod.unit}
          overallRating={prod.overallRating}
          likes={prod.likes}
          userID={route.params.userEmail} 
        />
       )}
       keyExtractor={(prod,index) => {
         return prod._id
       }}
     />
   </ScrollView>
 </View>

2

Answers


  1. The object passed to the renderItem function has the following properties:

    renderItem({
      item: ItemT,
      index: number,
      separators: {
        highlight: () => void;
        unhighlight: () => void;
        updateProps: (select: 'leading' | 'trailing', newProps: any) => void;
      }
    }): JSX.Element;
    

    In other words, the product is in the item property. Your current code attempts to destructure a property named prod, which doesn’t exist.

    FlatList renderItem property docs


    Unrelated

    IMO the ProductCard usage should look closer to this:

    <ProductCard 
      cardType="social"
      product={item}
      userID={route.params.userEmail} 
    />
    

    There’s no (good) reason to force passing each product property separately. You could allow optional properties in case you want to override the values in the product itself, though.

    Login or Signup to reply.
  2. the function renderItem of FlatList passes a parameter with an item attribute, representing an item in the list, and also I believe you don’t need the ScrollView with FlatList, as FlatList has the horizontal attribute, try switching to this code:

    <View style={styles.prodCont}>
     <FlatList
     horizontal
     data={products}
     renderItem={({ item }) => (
        <ProductCard 
          cardType="social"  
          title={item.title} 
          imageUrl={item.imageUrl} 
          price={item.price} 
          unit={item.unit} 
          overallRating={item.overallRating} 
          likes={item.likes} 
          userID={route.params.userEmail} 
        />
     )}
     keyExtractor={(prod,index) => prod._id}
     />
    </View>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search