0

I am sorting array in 'onChange' method and setting it up with 'setState' but after that it's rendered unsorted;

I've update function

// this method is called as a callback from component (on component change)
async onSomeComponentUpdate(data) {
 let newData = [];
 // ... some sorting fctions
 console.log(newData); // it's sorted here
 this.setState(state=> ({data: newData}));
}

After that I'm logging the render fction

render() {
  // data are still sorted here
  Object.keys(this.state.data).map((key) => {
     console.log(this.state.data[key]);
  });

  // but down here it is not sorted
  return (
     {Object.keys(this.state.data).map((key) => {
        return (this.SomeComponentRow(key,this.state.data[key]))
     })}
  );
}

and the component function with binded onUpdate

SomeComponentRow(key, item) {
   return <SomeComponent key={key} item={item} onUpdate={this.onSomeComponentUpdate} />;
}
  • Can you create a minimally, *working* component that shows the issue? – Phillip Jul 10 '19 at 12:38
  • 2
    Why are you using `Object.keys` with an array? `this.state.data.map...` should be just fine. Are you sure `state.data` is always an array? Also please provide [mcve] – Yury Tarabanko Jul 10 '19 at 12:39

1 Answers1

0

Object.keys does not guarantee the order. If order matters, you need to use an array instead (you can find more info here)

Gaël S
  • 1,598
  • 6
  • 15
  • Thank you I'll try usual `for`. But how it is possible to have different (by order) values logged in same function (`render()`) and different after being rendered? –  Jul 10 '19 at 12:38
  • Because you perform twice an `Object.keys` therefore, you get differet order. However, if you save `Object.keys` in a variable, you would probably get the same result – Gaël S Jul 10 '19 at 12:45
  • Map() of array instead of object works well. `this.state.data.map((key) => { ... });` –  Jul 10 '19 at 12:45
  • check my previous comment :) But why you perform an `object.keys` if it's an array ? You avoid lines of code and improve readability by using a `.map` – Gaël S Jul 10 '19 at 12:47
  • Traversing of keys follow these rules in Object - First, the keys that are integer indices, in ascending numeric order. Then, all other string keys, in the order in which they were added to the object. Lastly, all symbol keys, in the order in which they were added to the object. – Monika Mangal Jul 10 '19 at 12:49
  • If you want to read more about it - https://2ality.com/2015/10/property-traversal-order-es6.html#traversing-the-own-keys-of-an-object – Monika Mangal Jul 10 '19 at 12:49