I have a Next.js project with Redux. In my store, there is an array of state which updates via Redux reducers. Basically an array of state I use a lot, across some components.
In one of my reducers, I sort this array. The array is full of objects, which I sort through a specific property. When I console.log
the array, it seems to have sorted fine.
In one of my components, I have this sorted state mapped through. I've simplified the logic here.
names.map((p) => (
<div key={p.name}>
{p.firstname} {p.lastname}
</div>
));
When the HTML shows though, all of the elements are not in the correct order. The last couple dozen div
elements seem ordered, but the first dozen are seemingly random.
For example, here is the array.
let names = [
{
"firstname": "Michael",
"lastname": "Scott",
},
{
"firstname": "Jim",
"lastname": "Halpert",
},
{
"firstname": "Dwight",
"lastname": "Schrute",
},
{
"firstname": "Pam",
"lastname": "Beesly",
},
{
"firstname": "Ryan",
"lastname": "Howard",
}
]
When sorted, console logging returns the expected result. Here is the sort function.
names = names.sort((a, b) => a.firstname.localeCompare(b.firstname))
The resulting HTML should look something like this.
Instead, the results are scrambled around for some reason. I suspect this is due to Redux editing the state, but I have no clue why.
As I know this is a broad error, I am happy to provide any extra context if my code is too simplified. Answer would be much appreciated but anything to help narrow down where the problem lies, would be especially useful.