0

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>
    </>
  );
};
  • 1
    Are you saying this just because it doesn't log what you expect, or because the view doesn't update? – Adam Jenkins May 05 '21 at 16:40
  • @Adam when I click the search button first time, the function should run and sort the data but it does not do that console.log(filteredData, 'fd'); return undefined but as soon as I click the search button the filter logic works and console.log(filteredData, 'fd') prints the filter data. why it is not filtering the data on the first time? – birdsandwich May 05 '21 at 16:45
  • 2
    You didn't answer my question - forgetting about the console.log's, is the view updating correctly? – Adam Jenkins May 05 '21 at 16:50
  • @Adam yes the view is getting updated on the first click itself. But in my real project (which I am not showing here, this is just mimic of that) I have the same condition as here but it shows error in there. – birdsandwich May 05 '21 at 16:55
  • Then you should show the real problem you are trying to fix. `setState` is `asynchronous` - check the dupe. I was about to mark this as a dupe for the same question, but figured I'd ask first. If you're still having problems in your real project, open a new question with your real problem. – Adam Jenkins May 05 '21 at 16:58
  • @Adam dupe is class component and this functional but I thought execution pattern would be different – birdsandwich May 05 '21 at 17:05
  • It is not different. – Adam Jenkins May 05 '21 at 17:26

0 Answers0