Sorting redux state array

I’m trying to sort products based on their price, I created two actions, for lowest and highest price. The problem is when I dispatch the actions displayed products disappears, they are undefined although they are in state…

I read about componentWillReceiveProps but don’t know how to use it in this case…

Here is the component:

<div>
            <Button.Group className="buttonGroup">
                  <Button onClick={this.props.sortProductsByLowestPrice}>Lowest price</Button>
                  <Button onClick={this.props.sortProductsByHighestPrice}>Highest price</Button>
            </Button.Group>
            <div className="horizontal">
              {this.props.products ?
                 this.props.products.slice(0,5).map((product) => {
                return <ProductItem key={product._id} product={...product} />
                 }) : <Loader active inline />}
            </div>
           </div>

Here are the actions:

export const sortProductsByLowestPrice = () => (dispatch, getState) => {
      let products = getState().products.products.products;
      const isArray = Array.isArray(products);
      const sorted = products.slice().sort((a,b) => { return a.price > b.price})
      console.log(sorted);
      dispatch({
        type: SORT_PRODUCTS_BY_LOWEST_PRICE,
        payload: sorted
      })
      
}


export const sortProductsByHighestPrice = () => (dispatch, getState) => {
      let products = getState().products.products.products;
      const isArray = Array.isArray(products);
      const sorted = products.slice().sort((a,b) => { return a.price < b.price})
       console.log(sorted);
      dispatch({
        type: SORT_PRODUCTS_BY_HIGHEST_PRICE,
        payload: sorted
      })
}

Sort functions need to return an integer, not a boolean.

Thank you but it works, that’s not the problem…

Ok, could you,

  1. Please show us all of your code as the problem is probably not where you expect it to be?

  2. Tell us what you mean by “they are undefined although they are in state…”? Are you inspecting with some tool?

In the logger I see the next state which has products property but they are not displayed, beside the code I provided I have mapStateToProps and mapDispatchToProps…

It would help to see your reducers and your initial state, but it is better to just post a link to your code (Github, Codepen, etc) than to assume you’re giving people the information they need. If you knew where the problem was, you’d have fixed it yourself. My best guess right now is that you’re dispatching the wrong type.

Here is the Stackblitz link: https://stackblitz.com/edit/react-sshop

You won’t be able to see it working, only code…