{ return (
Login Or Sign up

All useState vars like rowData are null/empty when I print from a cellrendered button within AgGrid

36 Views Asked by At
const [groupColumnDefs] = useState([
    {
      field: "groupName",
      flex: 4,
    },
    {
      field: "Delete",
      flex: 1,
      cellRenderer: (params: any) => {
        return (
          <Button
            className="p-2 w-16 my-1 flex justify-center"
            onClick={() => deleteRow(params)}
            color="red"
          >
            Delete
          </Button>
        );
      },
    },
  ]);

const deleteRow = (params: any) => {
    console.log(params);
    console.log(userGroupData);
};

the rowData is userGroupData

When I print userGroupData from clicking the cell rendered delete button, it prints an empty list. The delete button is there because there are two rows in the userGroupData list. Why can't I access these values in that particular function? Is it in a weird scope or something?

1

There are 1 best solutions below

0
Tawfeeq Amro On

You need to separate UI from state, I don't recommend to put Delete button inside State, use callback to delete item and update the userGroupData like this:

const deleteRow = useCallback((params: any) => {

const updatedData = userGroupData.filter((row: any) => row.id !== params.data.id);

setUserGroupData(updatedData);

}, [userGroupData]); 

After that you can use useMemo to set groupColumnDefs like this

 const groupColumnDefs = useMemo(() => [
{
  field: "groupName",
  flex: 4,
},
{
  field: "Delete",
  flex: 1,
  cellRenderer: (params: any) => (
    <Button
      className="p-2 w-16 my-1 flex justify-center"
      onClick={() => deleteRow(params)}
      color="red"
    >
      Delete
    </Button>
  ),
}
  ], [deleteRow]); 

I tried that on my own IDE is working...