I have a problem trying to push objects to arrays in react. When I push an element, React modifies the main item. (I need it empty)
I have this code. 2 empty arrays.
const serviceDefault = {
name: "",
type: "",
panels: [],
paint: [],
hardware: [],
workforce: [],
};
const productDefault = {
product_id: "",
name: "",
quantity: 0,
section: "",
cost: 0,
};
Then I have the Hook with the const services (An empty array)
const ProjectEstimates = () => {
const [services, setServices] = useState<any>([]);
....
A handler pushes serviceDefault TO services
const handleAddService = () => {
setServices([...services, serviceDefault]);
};
Another handler pushes productDefault TO services[index].panels
THE ERROR HAPPENS HERE.
const handleAddItem = (serviceIndex:any) => {
const newServices = [...services];
newServices[serviceIndex].panels.push(productDefault);
setServices(newServices);
}
The problem is, when it pushes the productDefault to an especific index of services array should modifies only services array, but the main empty array serviceDefault is modified too. So, the next pushes will be start to push the previous item...
I can`t see the error, i don't have a function that modifies serviceDefault.