Im building a react table, which shows rows for every person, and who he voted for.
This is my index.js:
function Tables() {
const { columns, rows } = votersTable();
return (
<DataTable
table={{ columns, rows }}
isSorted={false}
entriesPerPage={true}
showTotalEntries={true}
noEndBorder
canSearch={true}
/>
);
}
When updating (via a button) who the perosn voted for, in votersTable() as follows:
const handlePresidentChange = (event, newPresident, rowId, pid) => {
// Update the selected value for the specific row
const updatedPersonData = {
speculation: newPresident,
// Add other updated fields here
};
updatePerson(pid, updatedPersonData)
.then(() => {
// Create a copy of the current electorsList
const updatedList = [...electorsList];
// Find the index of the object with the same id in the copied array
const indexToUpdate = updatedList.findIndex((person) => person.id === pid);
// If a matching object is found, update its president property
if (indexToUpdate !== -1) {
updatedList[indexToUpdate].president = newPresident;
// Update the state with the new array
setElectorsList(updatedList);
}
})
.catch((error) => {
console.error("Error updating data in Firestore:", error);
});
//Should send a write command to firestore
};
The whole DataTable components gets re-rendered again.
How can I prevent that?
I tried disabling setElectorsList(updatedList), it doesnt cause a re-render, but this doesnt update the line. Only after a refresh and when the web extracts the data from firestore, I see the correct updated value.
>Solution :
Ok,lets talk a little about re-rendering process in react.
a component, will always re-renders if any state in parent component changes,or if component’s own Props changes.
when props change, the component will re-renders to make sure everything is updated.
in your example,as you said, columns and rows change when we use voterTable button. they are props in DataTable, so they make DataTable to re-renders. when props changes, re-render is inevitable.