4
I have a table where I want to sort your data.
The table is copulated through the values of this useSelector()
const users = useSelector(state => state.userStates.users)
When the user clicks on one of the table columns, I send it to the function sortBy()
the key I will command:
<TableCell onClick={() => sortBy('login')}>Email</TableCell>
And then my function performs the ordination:
const sortBy = (key) => {
// If is using a field different by the last, starts ordering in asc
if (key !== orderingField) {
setOrderingStatus('asc')
setOrderingField(key)
// Reverte a ordenação
} else {
if (orderingStatus === 'asc') {
setOrderingStatus('desc')
} else {
setOrderingStatus('asc')
}
}
let copyUsers = {}
copyUsers.data = [...users] // make a copy of the obj
copyUsers.lastPage = JSON.parse(JSON.stringify(lastPage)) // copy of the last page
copyUsers.data.sort(compareValues(orderingField, orderingStatus)) // make the sort)
dispatch(userActions.setUserList(copyUsers))
}
export default function compareValues(key, order = 'asc') {
return function innerSort(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}
const varA = (typeof a[key] === 'string')
? a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string')
? b[key].toUpperCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return (
(order === 'desc') ? (comparison * -1) : comparison
);
};
}
The data is being sorted correctly through this function, however, when I perform the dispatch()
of that object I get several errors:
Child already has a Parent, it must be Removed first. nbind.js:9812 Uncaught abort() at Error
I believe it is something in the copy of the object users that is the problem, but I still can not understand what is happening and how to solve.
copyUsers.data = [...users] // Funciona
copyUsers.data = JSON.parse(JSON.stringify(users)) // Da o erro
copyUsers.data = [...users] // Da o erro
The code calls in the search the
dispatch
, really weird.– novic
@Virgilionovic for what I debugged, if I order the copyUsers.data object = [...users] copied in this way, he gives this error, the same happens if I try with JSON.parse(JSON.stringify()) and other methods that copy the object. I had to pass the object without copy, and then it worked.
– veroneseComS
I’d really like to understand why this is happening.
– veroneseComS
copyUsers.data = [...users] // make a copy of the obj
, shouldn’t becopyUsers.data = {...users]}// make a copy of the obj
– novic
@Virgilionovic doesn’t think so, because the users object is an array, if I put {...users} it puts my users inside another object, when I print console.log(copyUsers.data) I have the object array as expected, he even draws lots, but when I tell him to make that mistake.
– veroneseComS