1

I have a function for handling sorting for my menu array but I am not sure how to code it correctly. I might be missing something like map but I am not sure. On button click, it should update the state and render the menus sorted alphabetically. The code I have below doesn't cause anything to render when I click the button since either. Also how would I implement the fetchMenus into the handleMenuSort function correctly so that it fills the array?

Edit

class MenuFilter extends Component {
  constructor() {
  super(); 
  this.state = { menus: [] };
}

handleMenuFetch = e => {
    this.props.fetchMenus()
};

handleMenuSort = e => {
  this.setState(state => {
      this.state.menus.sort(function(a, b) {
      if (a.name < b.name) {
        return -1;
      }
      if (a.name > b.name) {
        return 1;
      }

      return 0;
    })
  });
}

render() {
  return (
    <Container>
        <Row>
          <div>
              <button id="menu-show-button" onClick={this.handleMenuFetch}>Show Menus</button>
          </div>
          <div>
              <button id="sort-button" onClick={this.handleMenuSort}>Sort Menus</button>
          </div>
        </Row>
    </Container>
    )
  }
Jabba the Hutt
  • 654
  • 3
  • 15

1 Answers1

1

The issue is that you are mutating state. One option is to make a shallow copy of your menu array using the spread operator, and then sorting that array.

this.setState({
    menus: [...this.state.menus].sort(function(a, b) {
      if (a.name < b.name) {
        return -1;
      }
      if (a.name > b.name) {
        return 1;
      }

      return 0;
    })
});
Nick
  • 16,066
  • 3
  • 16
  • 32