In a table i am integrating search functionality based on two parameters based on bank and rate
When i click on Submit i want the set the state of the array to be updated twice first it will initialize will the global array after the results are filtered the updated value should be updated in the state
const [fixedDepositNriRates, setFixedDepositNriRates] = useState([]);
const [testData, setTestData] = useState([]);
const SearchResults = () => {
setFixedDepositNriRates(testData);
let data = [...fixedDepositNriRates];
if (bank) {
data = data.filter(item => item.Group.indexOf(bank) !== -1)
}
if (rate) {
if (rate === 8) {
data = data.filter(item => item.interest < rate)
}
if (rate === 9) {
data = data.filter(item => item.interest > rate)
}
if (rate === 10) {
data = data.filter(item => item.interest > rate)
}
}
setFixedDepositNriRates(data);
}
I got the filtered result in the variable data but i am not able to set the state as
setFixedDepositNriRates(data);
2
Answers
you want to directly update
fixedDepositNriRates
with the filtered results. In that case, you can use a callback in yoursetState
function to ensure that you’re working with the most recent state.The
fixedDepositNriRates
is the result of filtering (if needed) thetestData
. You don’t need to clone thetestData
, and then filter and setfixedDepositNriRates
. Just filter thetestData
before you set it tofixedDepositNriRates
.In addition, you can extract the filtering logic to a
filterResults
function, and do the entire filtering in a single step: