Home > Software design >  cannot react property 'forEach' of undefined
cannot react property 'forEach' of undefined

Time:01-01

#React Native I'm trying to get the data from array to picker. Array sends the data to the picker without any problem but when I select an item in the dropdown list " cannot react property 'forEach' of undefined This error pop up

 const ListItem = ({ item, onSubtract, onAdd }) => (
        <View
            style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center',
            }}>
            <View style={{ flexDirection: 'row', flex: 1, alignItems: 'center' }}>
                <Text style={styles.cardText} >{item.name} - </Text>
                <Text style={styles.cardText} >{item.price}</Text>
            </View>
            <View style={{ flexDirection: 'row', flex: 1, alignItems: 'center' }}>
                <Button title="Subtract" onPress={onSubtract} />
                <Text style={styles.cardText} >{item.quantity}</Text>
                <Button title="Add" onPress={onAdd} />
            </View>
        </View>
    );
    
    const ExistingCustomerScreen = () => {
        const [products, setProducts] = React.useState([
            { _id: 1, name: 'Item 1', price: 50, quantity: 0 },
            { _id: 2, name: 'Item 2', price: 29, quantity: 0 },
            { _id: 3, name: 'Item 3', price: 200, quantity: 0 },
        ]);
    
        const [products2, setProducts2] = React.useState()
    
        const onSubtract = (item, index) => {
            const nextProducts = [...products];
            nextProducts[index].quantity -= 1;
            setProducts(nextProducts);
        };
    
        const onAdd = (item, index) => {
            const nextProducts = [...products];
            nextProducts[index].quantity  = 1;
            setProducts(nextProducts);
        };
    
        let totalQuantity = 0;
        let totalPrice = 0;
        products.forEach((item) => {
            totalQuantity  = item.quantity;
            totalPrice  = item.quantity * item.price;
        });
    
        return (
            <SafeAreaView style={{ flex: 1 }}>
              
    
                <View style={styles.container}>
                    <Picker
                        style={{ color: '#000' }}
                        selectedValue={products}
                        onValueChange={setProducts}
                    >
                        {products !== "" ? (
                            products.map(item => {
                                return <Picker.Item label={item.name} value={item.id} />;
                            })
                        ) : (
                            <Picker.Item label="Loading..." value="0" />
                        )}
                    </Picker>
                </View>
    
    
                <FlatList
                    data={products}
                    renderItem={({ item, index }) => (
                        <ListItem
                            item={item}
                            onSubtract={() => onSubtract(item, index)}
                            onAdd={() => onAdd(item, index)}
                        />
                    )}
                    keyExtractor={(item) => item._id}
                />

            </SafeAreaView>
        )
    }

#React Native I'm trying to get the data from array to picker. Array sends the data to the picker without any problem but when I select an item in the dropdown list " cannot react property 'forEach' of undefined This error pop up

CodePudding user response:

It looks like you're setting the products state to a non array value based on this validation check in your code:

products !== ""

Therefore, products.forEach outside the validation will result in an error.

CodePudding user response:

In your Picker component, you are calling setProducts in the prop onValueChange.

You are basically saying to call setProducts() when the value changes, which is why products becomes undefined.

You could consider adding another state like selectedProduct instead.

  • Related