Table is not rendered again after a setState

Asked

Viewed 32 times

1

I have a table of Material React Ui and I’m trying to accomplish sort in the data.

After the array is sorted, my table is not being rendered with the new positions set by sort.

I already checked the function and checked that the elements are having their positions changed, but the table does not render these changes again.

What I tried to:

const [users, setUsers] = useState([])

    const sortBy = (key) => {
        let teste = users.sort(compareValues('login', 'desc'))
        setUsers(teste)
        console.log(users)
    }

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
          );
        };
    }

In my template:

<TableContainer component={Paper}>
            <Table aria-label="simple table">
                <TableHead>
                <TableRow>
                    <TableCell onClick={() => sortBy('email')}>Email</TableCell>
                    ...

I’m using the user.id key to my map:

{users.map(user => (
                    <TableRow key={user.id}>
  • Could you put the complete component? It’s a bit confusing so if possible also format the identation correctly

  • @Costamilam I managed to solve with the help of gringo stackoverflow

1 answer

1


My problem was because by changing the array order, React still fills that component has the same state, so it is not rendered again.

It was necessary to create a copy of the object:

const sortBy = (key) => {
        let teste = [...users] // make a copy
        teste.sort(compareValues(key, 'desc')) // sort
        setUsers(teste)
    }

And then the ordering was done and rendered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.