Reputation: 1216
I have a problem where, I am sorting prices from high to low and low to high. The problem is that, when I click either of them at first, it doesn't change anything, it does not sort. But when I click again, it sorts according to what I clicked.
this is the Search class:
export default class Search extends Component{
state = {
item: [],
sortValue: "none"
}
sort = (e) => {
console.log("this.state.sortValue", this.state.sortValue)
this.props.sort(this.state.sortValue)
this.setState({
sortValue: e.target.value
})
}
then, my render
<div className="col-6 col-lg-7 col-sm-7 col-xs-7">
<select className="form-control form-control-sm" id="exampleFormControlSelect1" value={this.state.sortValue} onChange={this.sort}>
<option value="none">None</option>
{/* <option>Rating</option> */}
<option value="priceLowToHigh">Price Low to High</option>
<option value="priceHighToLow">Price High to Low</option>
</select>
</div>
Here is my dataSort var:
var dataSort = [
{
name: "Price: Low to High",
value: "price-low-to-high"
},{
name: "Price: High to Low",
value: "price-high-to-low"
},{
edit: forgot to add this:
sort = (sortData) => {
console.log("data", sortData)
var obj = []
var { data } = this.state.items2
if(sortData === "priceLowToHigh"){
this.setState({
items2: {
data: data.sort(asc),
meta: this.state.items.meta
}
})
}else if(sortData === "priceHighToLow"){
this.setState({
items2: {
data: data.sort(desc),
meta: this.state.items.meta
}
})
}else if(sortData === "none"){
this.setState({
items2: this.state.items
}, () => {
this.onSearch()
})
}
}
Upvotes: 1
Views: 1087
Reputation: 34014
The issue is that you are passing sortedValue state to props sort and that’s why it works from second time. The reason the state property sortedValue has previous value because you are first passing state to sort and then you are actually modifying it with event using setState. Even if you do setState and then pass state property sortedValue to props sort it won’t work because the state value gets updated with new value only when the component renders.
So, pass event.target.value directly to props.sort
sort = (e) => {
console.log("this.state.sortValue", this.state.sortValue)
this.props.sort(e.target.value)
this.setState({
sortValue: e.target.value
});
}
Upvotes: 1