Safari renders element of array in different order on each render

Viewed 240

I have the following code:

Object.values(data).map((user) => {
  <div>
    <User key={user.id} user={user} />
  <div>
})

And the user has an ability to add new users through the UI, which get added to the data object and hence triggers a render.

It's working perfectly fine on all browsers (Chrome, Edge, IE) except from Safari. (version 13.1.2) On Safari, almost each re-render of that users list changes the display order of those users in the UI.

Why could it be?

1 Answers

There is no JavaScript standard that says getting keys or values from an object should come in a certain order:

According to mdn Object.values

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop

And following the for...in link it says:

A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting).

The reason it isn't guaranteed in a particular order was because of IE but since Safari is new IE it has taken over the torch of unpredictability.

If item order are important you should store them in an array, Set or Map.

Related