Reputation: 85765
I am using react-table with mbox and have run into a issue where my state is not updating.
I have a table like this
<ReactTable
data={data}
columns={columns}
showPageSizeOptions={false}
resizable={false}
className="-striped -highlight"
defaultPageSize={12}
filterable={true}
/>
A column that has
{
Header: "",
accessor: "checkbox",
filterable: false,
width: 35,
Cell: ({ original }) => {
return (
<input
type="checkbox"
className="checkbox"
checked={employeeUiStore.selectedEmployees.indexOf(original.id) >= 0 }
onChange={() => employeeUiStore.toggleCheckbox(original.id)}
/>
);
}
},
and a store like this
class EmployeeUiStore {
@observable addMode = false;
@observable selectedEmployees = []
constructor(){}
@action
toggleCheckbox(employeeId) {
const index = this.selectedEmployees.indexOf(employeeId);
if(index === -1){
this.selectedEmployees = [...this.selectedEmployees, employeeId];
}else {
const newSelectedEmployees = [...this.selectedEmployees];
newSelectedEmployees.splice(index, 1);
this.selectedEmployees = newSelectedEmployees;
}
}
@action
toggleAddEmployee(){
this.addMode = !this.addMode;
}
}
export default EmployeeUiStore;
The weird thing is if I add something like this to my code
console.log(employeeUiStore.selectedEmployees.indexOf(0) >= 0)
Then states will update properly but when I remove this line then nothing is updated.
I see that my toggleCheckbox is being triggered and the state is being updated.
I also do have @observer on this component.
Upvotes: 4
Views: 5755
Reputation: 112787
You are not dereferencing anything when you pass the data
array to the ReactTable
component.
You can resolve this by either using slice
or peek
on the array before you pass it to external libraries:
<ReactTable
data={data.slice()}
columns={columns}
showPageSizeOptions={false}
resizable={false}
className="-striped -highlight"
defaultPageSize={12}
filterable={true}
/>
There is also no need for immutability in MobX. You can alter the array straight away:
class EmployeeUiStore {
@observable addMode = false;
@observable selectedEmployees = [];
@action
toggleCheckbox(employeeId) {
const index = this.selectedEmployees.indexOf(employeeId);
if (index === -1) {
this.selectedEmployees.push(employeeId);
} else {
this.selectedEmployees.splice(index, 1);
}
}
@action
toggleAddEmployee(){
this.addMode = !this.addMode;
}
}
export default EmployeeUiStore;
Upvotes: 3