Remove row from antd table on row button click

Viewed 1515

I am trying to remove data row from antd table, I am using the below code, when I hit delete button my dataset is empty.

Please help, Thanks in advance...

I am loading data from API code is as under

    const LoadAttendance = async() => {

    setLoading(true);
    //setData([]);

    let url = window.$api_url + '/teacher/myattendance';
  
    await axios.get(url)       
    .then(async response => {
        const actualData = await response.data;
      
        if (response.status == 200) {

            //setData(actualData);
            setData(actualData)
            console.log("actualData " + JSON.stringify(actualData));

        }
        setLoading(false);

    })
    .catch(error => {

        setLoading(false);
    
    });


  };

    

My Antd table is look like this

return <div>

        <Table
            columns={columns} dataSource={data}
            rowKey="studentId" 
            pagination={false}

            />


</div>;

This is my delete function

    const handleDelete = async(stid) => {
    //Here is problem data is empty tried both ways data as well as...data
    console.log("Data source " + JSON.stringify([...data]));

    const myData = data.filter(item => item.studentId !== stid);
    
    setData(myData);
  };

and this is antd columns

let cols = [
            
            {
                title: 'Sr. #',
                width: 150,
                
                render: (text, record, index) => <span style={{fontWeight: 'bold'}}>
                {index+1}. &nbsp;

                  <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.studentId)}>
                    <a>Delete</a>
                  </Popconfirm>

              </span>
            }
]
1 Answers

Looks to possibly be a stale enclosure of your data state. I suggest trying a functional state update instead. The functional state update will update from the previous state instead of using what is closed over in any callback scope.

const handleDelete = (stid) => {
  setData(data => data.filter(item => item.studentId !== stid));
};
Related