0

I have two functions

let [selected, selectedIds] = React.useState<readonly string[]>([]);
  1. This function is stored the given id in the array
 const addSelectedIds = (id) => {
    // Adding id with some calculation
    selectedIds(id);
 }
  1. This function is use to check the given id is available in array or nott
checkSelectedIds = (id) => {
    const isSelected = (id) => selectedIds.indexOf(id) !== -1;  
// Which return false, but its already added from first method
    // Here i need isSelected value as true because its already added from first method
} 

These function is call with one onClick event like below

<tr onClick={() => {addSelectedIds(id); checkSelectedIds(id)}} ></tr> 

I need selectedIds array in the second method checkSelectedIds() where have to check the selected id is available in array or not, but in the checkSelectedIds() selectedIds are return null So thats why am getting null values in array

  • Not really an answer to your question but please notice that if `selected` is an array, updating the state should look something like `selectedIds([...selected, id]);`, not `selectedIds(id);` – secan Oct 19 '22 at 07:29
  • I would also add, to avoid confusion in your useState, maybe set the let arguments as [selected, setSelected] so you know the second argument is a setter for the first – Richard Price Oct 19 '22 at 07:31
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Fraction Oct 19 '22 at 07:39
  • @RichardPrice Thanks for the suggestion, I have changed the argument name – Developer007 Oct 19 '22 at 08:48

1 Answers1

0

Could you use a useEffect hook to run when the state of the "Selected" array changes and run it from there?

useEffect(() => {
  checkSelectedIds(id)
}, [selected]);

I presume in your case the functions are running concurrently, when you need the first to run before the second

Richard Price
  • 482
  • 4
  • 13
  • Thanks for suggestion, useEffect() cant solve my problem because i want call checkSelectedIds() after onClick – Developer007 Oct 19 '22 at 09:39
  • In the above example thats exactly what would happen. the useEffect is triggered by a change to the state of "selected" and as a result the "checkSelectedIds" function is called. If you call it prior to this state change you will run into race condition issues. I.e function 2 is called before function 1 – Richard Price Oct 19 '22 at 14:30