0

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.

IIWolF
  • 31
  • 7
  • You are directly modifying state. `[...services]` only creates a shallow copy. – CertainPerformance Sep 01 '22 at 02:34
  • Can you explain to me a little more your comment? – IIWolF Sep 01 '22 at 02:47
  • `newServices` is only a shallow copy of the *array*, all the elements are copy by reference, meaning they are references to the elements of the original array. `newServices[serviceIndex].panels.push(productDefault)` is the mutation. It's mutating the `newServices[serviceIndex].panels` object in the previous state. – Drew Reese Sep 01 '22 at 03:52

0 Answers0