bla
bla

Reputation: 1055

I'm setting a new state to a object, but my table don't render again this update

I have one material table that i'm trying to sort.

After the sort array happens, my table don't render again with the new positions. Why?

I already check and the elements is changing the position of the first state, but still don't rendering.

What i try:

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

    const sortBy = (key) => {
        let teste = users.sort(compareValues(key, '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
          );
        };
    }

So, in my template:

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

I'm using user.id for the key:

{users.map(user => (
                    <TableRow key={user.id}>

Upvotes: 0

Views: 68

Answers (1)

tomen
tomen

Reputation: 539

Well, it's pretty tricky. It's the way React functions. React will look if whether your state is changed or not. If state changes, it rerenders.

The problem is lying in this line:

let teste = users.sort(compareValues(key, 'desc'))

sort function modifies the original array, and you assign teste to it. It's like reference to the original array. (More advanced info, teste and users reference to the same memory address or technically speaking they are one). Let take an example, if you change the original array, e.g users[0] = 'something', teste[0] will change accordingly.

And by the way React looks at it, doesn't matter teste or users, they are still the same. Therefore state doesn't change, hence not rerendering.

You can do this:

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

Upvotes: 2

Related Questions