I have a full repo here https://snack.expo.io/8NOF1nuoW .
I'm trying to add some names and in on text change event I'm adding the object new data.
Since the array of object is a state variable. It is not reflecting on list.
If i add new data now then on next change of data the new data getting updated.
const [prodName, setProdName] = useState('');
var [data, setData] = useState(DATA);
const DATA = [
{
prodName: 'Screen Guard',
},
];
onPress={() => {
console.log(DATA);
DATA.push({prodName: prodName});
setData(DATA);
}}>
<FlatList
data={data}
keyExtractor={(item) => item.prodName}
extraData={data}
renderItem={({item}) => (
<View style={styles.listView}>
<Text style={styles.listViewText}>{item.prodName}</Text>
</View>
)}
/>
React don't know if you add data to an array, only if the reference of the array change. Flatlist is the same.
So to create a new reference to an array, you create a new array.
const onPress={() => {
setData([...data, {prodName: prodName}]);
}}>
Syntax:
[...data]
create a new array by copying the data
into a new created array []
, it's called spread operator. Documentation here