1

I'm trying to read all checked items and storying that value to selectedTransaction.

Issue is when I check the 1st item, it throws undefined error & for the selection of the 2nd Item it shows 1 array item in the console log.

But if I console log the selectedTransactions, it shows correct item values.

What I'm doing wrong here. Please help

  const [selectedTransaction, setSelectedTransaction] = useState<any>();

  const handleCheckboxOnChange = (
    transactionDetails: TransactionDetail,
    isCheckeds: boolean,
  ) => {

    const selectedTransactions = transactionsList.transactionDetails
      .filter((item: TransactionDetail) => item.isChecked === true);
    setSelectedTransaction(selectedTransactions);

    console.log(selectedTransactions); // Shows 1 selected Item 
    console.log(selectedTransaction); // Shows undefined 
})

1 Answer 1

1

State is not updated immediately (its asynchronous and batched), thats why you are getting undefined or the previous state

setSelectedTransaction(selectedTransactions);
console.log(selectedTransactions); // Shows 1 selected Item 
console.log(selectedTransaction); // Shows undefined 

Use a useEffect to console state when data is changed. Give the dependency array [selectedTransaction]

useEffect(()=>{
    console.log(selectedTransaction); 
}, [selectedTransaction]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.