I am using useSelector() to get state and when I apply some filter to local state variable, my global state is mutating. Not sure why. Below is the code.
const filterVacations = (employees, status) => {
if(status === 'Approved') {
employees.forEach(item => {
item.vacations = item.vacations.filter(vac => vac.approved === true);
});
}
else if(status === 'Unapproved') {
employees.forEach(item => {
item.vacations = item.vacations.filter(vac => vac.approved === false);
});
}
return employees.filter(item => item.vacations.length > 0);
}
and calling this function as below:
const Vacations = () => {
const state = useSelector((state:State) => state);
const view = state.view;
const filter = state.filter;
const employees = state.employees;
employees = filterVacations(employees, filter);
return (
<>
//some component...
</>);
}
why is state is mutating here?
Its because you are not passing value when you say const filter = state.filter; but its passing reference.
For example, consider a Bookshelf having JS book on top of it in a Library. When you visit Libraria doesn't give you the copy of book but the location of the book. So if you tear page of the book and keep it same place. The librarian can aslo see torn page. But if you dont want this to happen. You need to get copy of the book and tear pages from it while the book on shelf will remain as it is.
So when you want to make the copy of the data and store it in a variable ES6 has introduced easy way to do it than earlier clumsy way. so this const filter = state.filter;
will become this const filter = [...state.filter]; // this makes copy of array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With