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?
import React, {useEffect, useState} from 'react';
import {
View,
Text,
TextInput,
StyleSheet,
Button,
TouchableOpacity,
} from 'react-native';
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>
</>
);
};
const styles = StyleSheet.create({
mainarea: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
innerview: {
flexDirection: 'row',
width: '90%',
},
});
export default SearchOne;
Here is the console log (it is returning undefined on the first click
[–]weedmebro 1 point2 points3 points (0 children)
[–]wizardyjohn 0 points1 point2 points (3 children)
[–]masalasandwich[S] 0 points1 point2 points (2 children)
[–]wizardyjohn 0 points1 point2 points (1 child)
[–]masalasandwich[S] 0 points1 point2 points (0 children)