Can not understand why filter is not working. The function get an object. If there is the same object in the state, the function delete this object from the state. If not, add to the state. The problem is that the object rewrites the state, but not add it to the state.
For example, object {a: 1, b: 2}
const [products, setProducts] = useState<any[]>([]);
const addObject = (data) => {
const sameData = !!products.find((item) => item.id === data.id);
const deleteData = products.filter((item) => item.id !== data.id);
const newData = sameData ? deleteData : [...products, data];
return setCheckedRoles(newData);
};
As a result I get not [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: 3}]; but only one object that come to function [{a: 1, b: 2}]
You want deleteData to run only when sameData is true, but instead it is running the moment you're defining it. (remember that filter() is being invoked)
To get the expected behaviour move the deleteData to be a function and execute it as per your wish
const [products, setProducts] = useState<any[]>([]);
const deleteData = (products) => products.filter((item) => item.id !== data.id);
const addObject = (data) => {
const sameData = !!products.find((item) => item.id === data.id);
const newData = sameData ? deleteData(products) : [...products, data];
return setCheckedRoles(newData);
};
Also please find a better name for the function addObject :)