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