bp123
bp123

Reputation: 3417

this.setState does not update state

I'm trying to use this.setState within handleFormSubmit however this.setState isn't updating and I'm not sure why. If I run console.log(updatePosition) before this.setState I can that all the data is there. What am I missing? I use similar code for handleChange and I don't have problems.

constructor(props) {
  super(props);

  let uniqueId = moment().valueOf();

  this.state = {
    careerHistoryPositions: [{company: '', uniqueId: uniqueId, errors: {} }],
  };

  this.handleFormSubmit = this.handleFormSubmit.bind(this);
}




handleFormSubmit(event) {
  event.preventDefault();
  const { careerHistoryPositions } = this.state;

  const updatePosition = this.state.careerHistoryPositions.map((careerHistoryPosition) => {
    const errors = careerHistoryValidation(careerHistoryPosition);
    return { ...careerHistoryPosition, errors: errors  };
  });

  console.log(updatePosition)
  this.setState({ careerHistoryPositions: updatePosition });
}

Upvotes: 0

Views: 821

Answers (2)

Boky
Boky

Reputation: 12064

Keep in mind that the state isn't updated immediately. If you want to check if it's updated use callback function. Something as follows:

this.setState({ careerHistoryPositions: updatePosition }, () => console.log(this.state.careerHistoryPositions);

From the docs :

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

Hope this helps.

Upvotes: 2

theRemix
theRemix

Reputation: 2224

You should show how you are calling handleFormSubmit chances are that it's bound to a Dom event. So this is not the class/component, instead if you console.log(this); you'll see that it's the Dom element, the form element.

To make your code work as intended, in your component constructor() method, add this to rebind the handler function to the react component's class method, and you'll have access to this.state and this.setState()

this.handleFormSubmit = this.handleFormSubmit.bind(this);

Upvotes: 0

Related Questions