material-table icon indicating copy to clipboard operation
material-table copied to clipboard

onSelectionChange and setState not working well

Open kyapwc opened this issue 7 years ago • 12 comments

Describe the bug Checkboxes do not get selected when setState is used alongside onSelectionChange. Currently using version 1.32.0

To Reproduce Steps to reproduce the behavior:

  1. Create a table and set a onSelectionChange()
  2. do a this.setState() with the data taken from onSelectionChange
  3. Checkboxes does not get checked
  4. Example:
<MaterialTable
  columns={[...]}
  data={...}
  onSelectionChange={(data) => this.setState({ selectedOrders: data })}
  options={{...}}
/>

Expected behavior Checkboxes to be checked and state is set.

Desktop (please complete the following information):

  • OS: macOS
  • Browser: Firefox, Google Chrome
  • Version: Firefox Quantum Version 66.0.3 (64 bit), Google Chrome Version 73.0.3683.103 (64 bit)

kyapwc avatar Apr 16 '19 01:04 kyapwc

Nevermind this issue, realized it was due to re-rendering of the component that made it not checked.

kyapwc avatar Apr 16 '19 06:04 kyapwc

How did you solve this issue?I am calling a function inside onSelectionChange inside which i am changing state. I there another way?

devat19 avatar Apr 30 '19 05:04 devat19

Hey @uplsaurabhA, there is a way, which is to do it like this:

handleCheckboxClick = (rowData) => {
  this.setState({
    selectedItems: {
      ...rowData,
      tableData: {
        checked: true,
      }
    }
  })
}

You can override the checkbox to be checked using material-table

It is a simple workaround and not logically correct but you have to set the logic toward it yourself. Just guiding in the right direction right now.

kyapwc avatar May 07 '19 07:05 kyapwc

With latest version you can call functions of material-table with tableRef. Did you check it?

mbrn avatar May 07 '19 07:05 mbrn

In case anybody still has trouble fixing this issue. You can either:

  1. Add shouldComponentUpdate check to force the material-table not to be re-rendered, or
  2. Change the data array which you feed into the material-table, please refer to #96 for detailed implementation

DeanDiDi avatar Oct 28 '19 03:10 DeanDiDi

I am trying to change state after onSelectionChange , but after changing the state , selection on the table is not shown in the UI , field is selected but its not showing in the UI. Please help

shasanka avatar Nov 27 '19 11:11 shasanka

as @DeanDiDi said, you should either cause the table to re-render (shouldComponentUpdate) or explicitly tell the row that it is selected - look at #96

tonypee avatar Jun 24 '20 05:06 tonypee

Instead of using useState, another way is to use useRef. useRef will not cause a re-render so it's independent of the component lifecycle, and in this case will cause the checkboxes to function normally, a simple fix, hopefully this helps someone. Also note that in order to get the array, you have to access the .current property in useRef.

const selectedRow = React.useRef([]);

const handleClick = rows => { selectedRow.current = rows; console.log(selectedRow: , selectedRow.current); };

//inside the material-table onSelectionChange={rows => { handleClick(rows); }}

Tellisense avatar Oct 14 '20 13:10 Tellisense

Is it possible to select all rows on current page?

amisoliman avatar Jul 20 '21 14:07 amisoliman

hi @Tellisense @mbrn , or other people who may help,

besides useRef, are there other ways to change the state of another object when onSelectionChange? I am facing an issue, which is whenever the table selection is changed, I want to toggle the disabled state of a button based on the selection. I have tried with useRef like below, but since the useRef does not trigger re-render, the button disabled style is not changed:

  const confirmSelectionBtn = React.useRef();
  
  const handleTableSelectionChange = (rows) => {
    if (confirmSelectionBtn && confirmSelectionBtn.current) {
      confirmSelectionBtn.current.disabled = rows.length === 0;
    }
  };

I think setState should be possible inside the onSelectionChange event, so I don't understand why material table does not support this. Or maybe I just missed how to make it happen?

And there is another issue I found out while solving this problem. If I:

  1. sort the table by a column, e.g. "birth year" column in my example,
  2. then select a row by checking the checkbox,
  3. then click on the Confirm button, which has nothing to do with the table, and I set a state inside the onClick event on the btn,
  4. then the table sorting and my selection are all gone / reset. but this only happens on the first time I load the page. If I repeat again without refresh, it works fine.

Should I report a new issue? But I suspect this has something with the onSelectionChange event. Here is my code:

const Overview = () => {
  // @ts-ignore
  const confirmSelectionBtn = React.useRef(null);
  const [data, setData] = React.useState<boolean>(false);

  const handleBtnClick = () => {
    setData(true);
  };

  const handleTableSelection = (rows: any) => {
    console.log(rows);
  };

  return (
    <div>
      <MaterialTable
        icons={tableIcons}
        title="Actions On Selected Rows Preview"
        columns={[
          { title: 'Name', field: 'name' },
          { title: 'Surname', field: 'surname' },
          { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
        ]}
        data={[
          { name: 'Mehmet', surname: 'Baran', birthYear: 1987 },
          { name: 'Zerya Betül', surname: 'Baran', birthYear: 2017 },
        ]}
        options={{
          selection: true
        }}
        onSelectionChange={(rows) => handleTableSelection(rows)}
      />

      <Button
        ref={confirmSelectionBtn}
        id="btn"
        name="btn"
        onClick={handleBtnClick}
        size="small"
      >
        Confirm
      </Button>
    </div>
  );
};

xiaochenzhang avatar Feb 04 '22 14:02 xiaochenzhang

Another fix is to make sure the state update resulting from the onSelectionChange call updates the value provided to the data property passed into MaterialTable.

Here's a sample:

<MaterialTable
    data={this.state.data}
    onSelectionChange={(rows, rowsData) => {
        const updatedData = data?.map((t) => {
              if (t._id === rowData._id) {
                 return {
                     ...t,
                     tableData: rowData.tableData,
                  };
               } else {
                    return t;
               }
          });
          
          this.setState({
              data: updatedData,
              selectedRows: rows,
           });
    })
/>

@xiaochenzhang This should resolve your issue

aiavci avatar Oct 30 '22 05:10 aiavci

I was facing the same issue and found out the useState name must be the same as MRT_RowSelectionState, after I changed it, it works:

If you are facing this issue when you select the checkbox and the UI doesn't update write your state like this (it's the same name they use in the docs, but I think it's not helpful because they don't make it clear):

// the state must be written like this since 
// MRT uses under the hood the state name to match the type MRT_RowSelectionState
  
 const [rowSelection, setRowSelection] = useState<MRT_RowSelectionState>({});

Just for your reference and to show what I meant above MRT_RowSelectionState type is:

export interface RowSelectionTableState {
    rowSelection: RowSelectionState;
}

felipehimself avatar Jan 09 '24 23:01 felipehimself