简体   繁体   中英

In React, how to assign data to state Object and capture state change in dataModel

I have react component in which I have two tables bring data independently via API. The records in table B depends upon row clicked in Table A. so I need to capture the table A click event along with data.

I have define const and setting its values with each click in table A. I am print out this value but I have realise the selectedScheduleId is one record behind. so lets say if in table A, previous value of scheduleId =10 and current is 12. Console.log( selectedScheduleId) will print 10. which is not correct. I want to change selectedScheduleId value as it coming from Table A.

Also How can I know that selectedScheduleId value is change so that I can refresh Table B?

const [selectedScheduleId, setSelectedScheduleId] = useState(0);

 const selectedScheduleRow = (row: any) => { 
    
  console.log("schedule clicked", row.row.original.eziScheduleId);

  if(row.row.original.eziScheduleId!=null && row.row.original.eziScheduleId!=0){
    setSelectedScheduleId(row.row.original.eziScheduleId);
    console.log("setSelectedScheduleId val  ",selectedScheduleId);
  }

在此处输入图像描述

component table

 return (
    <div>
    <h3>Table A</h3>
    <TableItemsTabs          
        apiUrl={api.EziTrackerSchedule}
    ></TableItemsTabs>

    <h3>Table B</h3>
    <TableItemsTabs          
        apiUrl={api.EziTrackerTransactionCollection}  // calling the API directly...
        columns={transactionColumns}
        customParams = {selectedScheduleId}  // this is where I am setting the ID
    ></TableItemsTabs>

Here just after assigning value to SelectedScheduleId you are doing a console.log which wont show you the updated value,what you really need to do is move your console.log from there inside a useEffect like below:

useEffect(()=>{
console.log(selectedSchedulId);
},[selectedScheduleId]);

this way you can test if selectedScheduleId has got changed or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM