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>
    )
  }

1 Answer 1

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;
    })
});
Sign up to request clarification or add additional context in comments.

Comments

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.