score:0

I think the problem may come from the fact that you try changing this.state directly in your method sortHandler before passing it to setState.

Try cloning this.state.data first: var clone = this.state.data.slice(0);

Then manipulate (sort) it, and finally assign it to your new state with this.setState({ data: clone })

Also, you may avoid calling multiple times this.setState() in your method, rather once at then end of your function.

score:0

I found several problems here.

First: don't assign state by this.state['arg']=. It's a bad practice. Use this.setState() instead.

Second: this.setState() it's asynchronous function, don't forget. Use callbacks. this.setState({ data }, () => anotherFunction())

In your case you can use lodash cloneDeep() method. It return deep copy of object, so you will not change original object. const data = _.cloneDeep(this.state.data).sort().

So. this.setState({ sortKey: e.target.dataset.sortcolumn }, () => putYourSwitchHere()); After that,

      this.setState({sortOrder: "ascending"});
        this.state.data.sort((a, b)=>{
          if (a[sortKey] < b[sortKey]) {
            return -1;
          }
          if (a[sortKey] > b[sortKey]) {
            return 1;
          }
          return 0;
        });
        break;

Try to use:

        const data = _.cloneDeep(this.state.data).sort((a, b)=>{
          if (a[sortKey] < b[sortKey]) {
            return -1;
          }
          if (a[sortKey] > b[sortKey]) {
            return 1;
          }
          return 0;
        });
   this.setState({sortOrder: "ascending", data});
   break;

You have already assign this.state.data, this.state.data = this.props.data will make a lot of errors in your last case.

score:0

The problem is in sortHandler function.

You are sorting the data using javascript sort() method. It is mutating method and doesn't create new object so React.js can't detect that the data has changed.

You should use non-mutating method.

Your code should be

const newData = this.state.data.concat().sort(...); 
this.setState({data: newData});

Related Query

More Query from same tag