2021-06-15
Here's an example of a bug I found recently. It was a list of users that occasionally displayed the wrong name with the wrong image. The data was stored as a JSON file and was using a
.sort()
operation before looping over each item. .sort()
is a mutating method and by adding a .slice()
before sorting we can create a shallow copy of the array to not alter the original data.A great way of finding out whether an array method is mutating or not is by using https://doesitmutate.xyz/
// React app
const data = [{ name: 'Test Testsson' }, { name: 'Aaron Aaronson' }];
// Incorrect
// The sorting operation that was used didn't really work as expected
// and since the sort method is mutating the original data
// we got some unexpected results
data.sort((a, b) => a.name > b.name).map((user) => <div>{user.name}</div>);
// Correct
// Use the slice method to create a copy of the array
// to not mutate the original data.
// Update the sorting operation to use localeCompare for better results
data
.slice()
.sort((a, b) => a.name.localeCompare(b.name))
.map((user) => <div>{user.name}</div>);