0

I'm working on a React app where you have a have a form where you can add a new employee and X number of dependents.

In the form, I set a default state like this:

class NewEmployee extends Component {
  state = {
    employees: [],
    costEstimates: { ...emptyCosts },
    relationshipOptions: [],
    newEmployee: { ...emptyEmployee }
  };

That emptyEmployee is coming from a const in a separate file, and it looks like this:

export const emptyEmployee = { firstName: '', lastName: '', dependents: [] };

I do this purely to just try and keep the initial state looking tidy in the code.

My problem is that the dependents array in emptyEmployee is getting modified, and I don't understand how. This is the function getting called when the user clicks to add a new dependent:

  handleNewDependent = () => {
    const newEmployee = { ...this.state.newEmployee };
    // blank dependent for now
    const dependent = {
      firstName: '',
      lastName: ''
    };

    newEmployee.dependents.push(dependent);

    this.setState({ newEmployee });
  };

I've pinpointed that this is when the dependents array of my emptyEmployee object gets modified. I don't understand how, since I use the spread operator to make a copy.

Andrio
  • 1,852
  • 2
  • 25
  • 54

0 Answers0