I'm trying to render items where each item has an item Name, item Price, and Item photos, like a todo list which works well but the first item on the list is always an empty array.
// Store State
const [itemName, setItemName] = useState('');
const [itemPrice, setItemPrice] = useState('');
const [photoArray, setPhotoArray] = useState([]);
const [storeItems, setStoreItems] = useState([]);
const addItem = {
id: Math.floor(Math.random() * 11),
itemName: itemName,
itemPrice: itemPrice,
photo: photoArray
};
const addStoreItem = () => {
if (itemName == '' || itemPrice == '') {
Alert.alert('Error', 'Please fill in the item detail.')
} else {
Keyboard.dismiss();
setStoreItems([...storeItems, addItem]);
setItemName(null);
setItemPrice(null);
setPhotoArray([]);
};
};
I'm rendering the item list in a bottomsheet Modal before adding it to the screen. PhotoArray
const pickPhoto = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
quality: 0.2,
});
if (!result.cancelled) {
setPhotoArray([...photoArray, result.uri]);
}
};
Render in bottomsheet modal
{storeItems.map((item, index) => {
return (
<View key={index.toString()} style={{flexDirection: 'row', marginBottom: 10, marginTop: 5}}>
<AddStoreItem items={item}/>
<TouchableOpacity style={styles.cancel} key={index} onPress={() => deleteItem(index)}>
<Image source={icons.cross} style={styles.cancelIcon}/>
</TouchableOpacity>
</View>
)
})
}
Send StoreItems to screen
const store = () => {
setStoreItems([...storeItems, addItem]);
storeRef?.current?.close();
Keyboard.dismiss();
};
Header component that has the submit button
<ModalHeader left={toggleStoreModalClose} right={store} />
Render in screen
{Array.from(Array(numColumns)).map((col, colIndex) => (
<View style={{flex: 1}} key={colIndex}>
{photoArray
.filter((item, index) => index % numColumns === colIndex)
.map((item, index) => (
<View key={index.toString()} style={styles.photoContainer}>
<Image source={{uri: item}} style={styles.addedPhoto}/>
</View>
))}
</View>
))
}
Can anyone please help?
CodePudding user response:
That's because in this line
setStoreItems([...storeItems, addItem]);
you are spreading storeItems
which is initially set to []
empty array, thus the issue of first item as empty array
CodePudding user response:
Found the Problem. Was passing addItem again in the function to the submit button
Before
const store = () => {
setStoreItems([...storeItems, addItem]);
storeRef?.current?.close();
Keyboard.dismiss();
};
And After
const store = () => {
setStoreItems([...storeItems]);
storeRef?.current?.close();
Keyboard.dismiss();
};
Thanks for all the effort.