1
class Form extends React.Component {
  constructor(props) {
    super(props);

    this.initialState = {
      name: "",
      job: ""
    };

    this.state = this.initialState;
  }

  handleChange = event => {
    const { name, value } = event.target;

    this.setState({
      [name]: value
    });
  };

  submitForm = () => {
    this.props.handleSubmit(this.state);
    this.setState(this.initialState);
  };

The code works okay. I just wonder what the "setState" function does In my perspective, after users submitting a form, it should empty the inititalState for further use. But after "handleChange", the initalState contains data. So why we have to reassign?

Rieder
  • 1,125
  • 1
  • 11
  • 18

2 Answers2

3

When you write this.state = this.initialState;, you set this.state to point to the same object that this.initialState points to, rather than creating a new object that is identical to this.initialState. So when the state is later changed, this.initialState is also changed. This is why your component still has non-empty data in its state even after calling this.setState(this.initialState);.

You can fix this by setting this.state equal to a copy of this.initialState, like this:

this.state = { ...this.initialState };

Note that things get a bit more complicated for nested objects (and arrays) where you'll need to do a deep copy of the object/array, but this solution works in this case.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
  • Thank you so much for the quick reply! I have one more question: in the "submitForm" method, after users submitting the form data, the firm should return blank right? Then users can submit new data through the firm. My code actually work but I just do not understand what is the function of "this.setState(this.initialState)" – Rieder Jan 28 '19 at 07:54
  • Really appreciate for the answer! – Rieder Jan 28 '19 at 10:13
  • @Rieder it seems that the point of `this.setState(this.initialState)` is to clear the form data. This might be useful if you have a button like "Create and Add Another" where you would send off your form data like a normal submit, but then stay on the same page but clear the existing form data. Does that help answer that? – Henry Woody Jan 28 '19 at 18:40
1

I don't want to confuse you more than you need to but I wanted to add some gotcha information on the above answer.

Like @Henry Woody stated this.state = { ...this.initialState }; works fine in your case, but if your React state includes arrays or nested objects (Anything passed through reference), you will need to deep clone your object in order to get rid of the nested reference therefore avoiding mutating them inadvertently:

From What is the most efficient way to deep clone an object in JavaScript?:

this.state = JSON.parse(JSON.stringify(this.initialState));
Saraband
  • 1,540
  • 10
  • 18