I am trying to update the state and filter the array data when I press the search button. However the the data gets filtered only on the second click, the first click returns undefined or does not update the state, but clicking it again the functionality works and state is updated?
const data = [
{
ID: '12345',
name: 'John',
age: '20',
},
{
ID: '67890',
name: 'Mike',
age: '21',
},
];
const SearchOne = props => {
const [id, setId] = useState('');
const [click, setClick] = useState(0);
const [filteredData, setFilteredData] = useState();
const searchit = enteredid => {
console.log(enteredid, 'enteredid'),
setFilteredData(data.filter(datasearch => datasearch.ID === enteredid));
console.log(filteredData, 'fd');
setClick(prevState => prevState + 1);
console.log('click', click);
};
return (
<>
<View style={styles.mainarea}>
<View style={styles.innerview}>
<TextInput
value={id}
onChangeText={text => {
setId(text);
}}
placeholder="Enter Search ID here"
/>
<Button
title="search"
onPress={() => {
searchit(id);
}}
/>
</View>
{filteredData && <Text> Filtered Data: {filteredData[0].name}</Text>}
</View>
</>
);
};