-1

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.

dwight, jim, micheal, pam, ryan

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.

rabbibillclinton
  • 410
  • 4
  • 17
  • 2
    If the array is in order when you do the `map`, the result will be in order in the DOM. (Some things you can do with CSS may make it seem like they aren't, but you probably aren't doing those things. You might be, though, of course.) If the result isn't in order in the DOM, that means the array isn't in order when you do the `map`. Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button). Stack Snippets support React, including JSX; [here's how to do one](http://meta.stackoverflow.com/questions/338537/). – T.J. Crowder Apr 15 '23 at 08:18
  • 1
    I guess that you sort the items after you do the map – Konrad Apr 15 '23 at 12:28

1 Answers1

0

I was sorting the array using a Redux reducer. Even though it console logged right, the order in which the elements were shown was wrong. While I still don't know why this happened, the solution was to not sort things in reducers.

In Redux, you should sort things through the selectors rather than directly in the reducers. By sorting things in my selectors instead of my reducers directly, the problem fixed itself.

rabbibillclinton
  • 410
  • 4
  • 17