Reputation: 77
Below is My code I am using dropdown and values, for example, clicking on January the 1 value is sent to function and states updates and that month record is shown but after that when I will try to see another month's data then it not showing. and when click on default I want to all data as it was previously. Thanks In Advance!
this.setState((prevState) => {
if (mon !== null || mon !== 0 || mon !== undefined) {
const rows = prevState.rows.filter((element) => {
return element.monthname === mon;
});
return {
rows,
};
} else {
const rows = prevState.rows.filter((element) => {
return element.monthname !== null;
});
return {
rows,
};
}
});
Upvotes: 0
Views: 1012
Reputation: 3718
don't use prevState
:
keep rowsOriginal
in the state alongside the rows
:
this.state = {
rows:[]
rowsOriginal:[]
}
componentDidMount(){
fetchRows().then(rows=>this.setState({rows:rows,rowsOriginal:rows})
}
then always filter from rowsOriginal
and set status to rows
:
this.setState({rows:rowsOriginal.filter((element) => {
return element.monthname === mon;
})})
When setting default:
this.setState({rows:rowsOriginal})
So,
if (mon !== null && mon !== 0 && mon !== undefined) {
this.setState({rows:rowsOriginal.filter((element) => {
return element.monthname === mon;
})})
}
else {
this.setState({rows:rowsOriginal})
}
Upvotes: 1
Reputation: 12181
Here you go with a solution
this.state = { filteredRow: [] }
this.setState((prevState) => {
if (mon) {
const filteredRow = prevState.rows.filter((element) => {
return element.monthname === mon;
});
return {
filteredRow
};
} else {
return {
filteredRow: prevState.rows
};
}
});
Use a separate state varaible to maintain your filtered rows.
Else condition filter is not required as you can directly show all the records. Filter
will unnecessary increase the compute by looping through data.
Upvotes: 1