Стас Рябцев
Стас Рябцев

Reputation: 1398

reactjs constant state for sorting

I am doing an array sorting. To do this, I store two variables in the state, one for the change array, the second for the array by default, so that I can return the original array back. However, when changing, both arrays change. How can I fix this? Is it possible to set some kind of constant? advise something? I need this.state.messagesDefault to be constant.

class Messages extends Component {

  state = {
    messages: [],
    messagesDefault: []
  };

  componentDidMount() {
    this.props.getMessages();
  }

  componentWillReceiveProps(nextProps) {
    console.log(333)

    this.setState({
      messages: nextProps.messages.messages,
      messagesDefault: nextProps.messages.messages
    })
  }

  onSort(type) {
    // when i call this function both arrays are changing, but i need this.state.messagesDefault to stay by default
    let messagesDefault = this.state.messagesDefault;
    if (type === 'all') {

    } else if (type === 'new') {
      messagesDefault.sort((a, b) => (a.notReaded) ? -1 : (a.lastMessage === b.lastMessage) ? -1 : 1);
    } else if (type === 'deal') {
      messagesDefault.sort((a, b) => (a.lastMessage === b.lastMessage) ? 1 : (a.accpet && a.accpet.author && a.accpet.executor) ? -1 : 1);
    }
    // console.log(messagesDefault)
    this.setState({messages: messagesDefault})
  }

  render() {
    console.log(this.state.messages)
    return (
      <div>
</div>
)
}
}

Upvotes: 0

Views: 29

Answers (1)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

Array.prototype.sort change the array reference so changing the actual array content. You need to make a copy first.

const messagesDefault = [3,4,5,6,7, 1,8];

const messages = [...messagesDefault].sort();

console.log(messagesDefault);
console.log(messages);

If your array contains objects and you want to change updated array's objects but don't want to change the objects in first one the you need to make copies of those objects as well becasue objects are references.

let messagesDefault = [ { title: 'Hello' }, { title: 'World' }];

let messages = [...messagesDefault].sort((a, b) => b - a);
messages[0].title = 123;

console.log(messagesDefault);
console.log(messages);

messagesDefault = [ { title: 'Hello' }, { title: 'World' }];

messages = messagesDefault.map(obj => ({...obj})).sort((a, b) => b - a);
messages[0].title = 123;

console.log(messagesDefault);
console.log(messages);

// If objects are nested, you need to make a deep copy

Upvotes: 3

Related Questions