Material-table: CheckBox doesnt check when i use REACT HOOK

Created on 3 Sep 2020  路  1Comment  路  Source: mbrn/material-table

I want to update checkBox status in 'onRowClick' event .

1  const handleRowClick = (evt, rowData) => {
2    const rslts = data;
3    const index = rslts.indexOf(rowData);
4    rslts[index].tableData.checked = !rslts[index].tableData.checked;
5    setData(rslts); 
6
7   // Random state update
8    setRandom(!random);
9   };

When i write code above it works but the application locked when i click repeatedly.

Note: Recommended solution for class component is code above except eighth line but i use function component.

Also if i remove eighth line, the following bug is happening;

2020-09-03-2145-55

Thanks for helping...

bug

Most helpful comment

This is not a bug with the table, this issue is with how you are setting state. Mutating the data and not assigning it a new reference before setting the state will result in React's reference check resulting in true and component not re-rendering.

Changing Line 5 to setData([...rslts]) will update the state of your component and re-render the table as well since data has changed

Assuming random is a boolean, since booleans are primitives and cannot be mutated is the reason your second setRandom on line 8 works.

But for arrays and objects in state always make sure to change the reference to the state before setting it. Your code will also work if you change line 2 as const rslts = [...data];

>All comments

This is not a bug with the table, this issue is with how you are setting state. Mutating the data and not assigning it a new reference before setting the state will result in React's reference check resulting in true and component not re-rendering.

Changing Line 5 to setData([...rslts]) will update the state of your component and re-render the table as well since data has changed

Assuming random is a boolean, since booleans are primitives and cannot be mutated is the reason your second setRandom on line 8 works.

But for arrays and objects in state always make sure to change the reference to the state before setting it. Your code will also work if you change line 2 as const rslts = [...data];

Was this page helpful?
0 / 5 - 0 ratings

Related issues

balibou picture balibou  路  3Comments

timrchavez picture timrchavez  路  3Comments

kfirshahar picture kfirshahar  路  3Comments

behrouz-s picture behrouz-s  路  3Comments

terapepo picture terapepo  路  3Comments