I have the following code in React,
let [employee, setEmployee] = useState([])
let employeeList = [
{
"data": [
{
"name": "John",
"email": "[email protected]",
"status": "passed"
},
{
"name": "Jane",
"email": "[email protected]",
"status": "failed"
}
]
}
]
When initilizing, we give as follows,
setEmployee(employeeList)
It shows both employees in table with status "passed" and "failed" in 2 rows correctly.
There is a selection box at the top which when selected with "passed",
we filter it with following function,
setEmployee(employee => employee[0].data.filter((ele, i) => ele.status === 'passed'));
I see the following filtered employee state variable,
// employee (state variable, see the original array of object of arrays is distorted here)
[
{
"name": "John",
"email": "[email protected]",
"status": "passed"
}
]
instead of,
[
{
"data": [
{
"name": "John",
"email": "[email protected]",
"status": "passed"
}
]
}
]
I’m new to React states and unable to achieve above format. The original employee state variable should be intact structurally but only its deep array should be filtered. I guess there is some mistake I make in line,
setEmployee(employee => employee[0].data.filter((ele, i) => ele.status === 'passed'));
Any help is very appreciated. Please don’t suggest advanced concepts like useMemo but let’s modify it slightly to achieve what I want. Thanks.
2
Answers
Not sure that I am getting the question right, but it seems that the state you are returning when the selection box is checked, you are return the state in a different structure.
The filter function is returning an array, but with a different structure when you first initialized your state employee.
I tried it out myself, and successfully filtered the employeeList without modifying the original structure of your initial state.
I am not sure if this would be an efficient algorithm for updating your state, but I hope this is a starting point for figuring out your problem.
happy coding
You can in the setter form of the
setEmployee
set the original object structure.Like so:
The above line basically returns the filtered result as an array value of the property
data
.Other approach would be use to clone the object and set normally, like so:
Note that I have used the
structuredClone
above to deep copy the old state object & to avoid any reference issues. Hope this helps. 🙂