0

Any clue why this code won't be able to do sorting properly base on columns?

sort(key){
    this.setState({
      [`toggle-${key}`]: !this.state[`toggle-${key}`],
      data: sortBy(this.state.data, [key], this.state[`toggle-${key}`]).map(v => v)
    })
  } 
  render() {
    return (
      <div style={styles}>
        <table>
          <thead>
            {Object.keys(this.state.data[0]).map(v => {
              return(
                <th onClick={()=>this.sort(v)}>
                  {v.toUpperCase()}
                </th>
              )
              })}
          </thead>
          <tbody>
            {this.state.data.map(v=>{
              return(
                <tr>
                  <td>{v.id}</td>
                  <td>{v.name}</td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
    );
  }

The toggling of the state seems to be correct but the reflection is only happening for the first time.

https://codesandbox.io/s/zqno7m7j4p

6
  • @KyleRichardson the 3rd argument isn't true and false? added a demo, I need to sorting to be able to toggle. Commented Dec 15, 2017 at 17:00
  • The third argument is supposed to represent the this value that you want indices of. Your code seems to be working as is though. The sandbox seems to work just fine. Sorting on both rows is working. Commented Dec 15, 2017 at 17:02
  • @KyleRichardson working but it can't toggle, I expect it to toggle. or I should use orderBy instead of sortBy? Commented Dec 15, 2017 at 17:05
  • So you want to be able to flip the order from asc to dsc and back in a column? I'll be back in a few. Commented Dec 15, 2017 at 17:11
  • Yes if you want to be able to asc and dsc you will need to use .orderBy. .sortBy will always be in asc order. Commented Dec 15, 2017 at 17:28

1 Answer 1

1

Lodash's _.sortBy() doesn't have the ability to select descending or ascending. Use _.orderBy() instead (sandbox):

sort(key) {
  const columnState = !this.state[`toggle-${key}`];

  this.setState({
    [`toggle-${key}`]: columnState,
    data: orderBy(
      this.state.data,
      [key],
      columnState ? 'desc' : 'asc'
    )
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

great! this is it. But I think it should be columnState ? 'asc' : 'desc'
Choose what you prefer. I didn't select asc : desc because the 1st click on id won't show any change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.