0

I have a problem with the function that counts the steps of a form.

this is undefined

nextStep = () => {
  const { step } = this.step;
  this.setState({
    step: step + 1
  });
}
export class FormUserDetails extends Component {
  continue = e => {
    e.preventDefault();
    debugger;
    this.props.nextStep();
  };
  render() {
    const { values, handleChange } = this.props;
    return (
      <div class="page">
        <h2 class="box-title">Who are you ?</h2>
        <form onSubmit={this.continue}>
          <div class="content">
            <input
              class="form-input"
              type="text"
              placeholder="Surname"
              name="firstName"
              defaultValue={values.firstName}
              onChange={handleChange}
              required
            />
TypeError: Cannot read property 'step' of undefined
UserForm.nextStep
src/components/form/UserForm.js:12
   9 |   email: ""
  10 | };
  11 | //proceed to the next steep
> 12 | nextStep = () => {
     | ^  13 |   const { step } = this.step;
  14 |   this.setState({
  15 |     step: step + 1

Thanks you for you help !

Clarity
  • 10,730
  • 2
  • 25
  • 35

2 Answers2

0

If the step is in the state then it can be fetched like this:

const { step } = this.state;
this.setState({
  step: step + 1
});
Clarity
  • 10,730
  • 2
  • 25
  • 35
Nagesh
  • 437
  • 3
  • 13
  • https://stackoverflow.com/a/48209870/4468021. Actually it's not wrong per se, but it might cause unexpected bugs along the way. Removed the downvote – Clarity Aug 22 '19 at 11:05
0

It'd be const { step } = this.state;

Also if your new state depends on the value of the current state, use functional form of setState:

  this.setState(state => ({
     ...state,
     step: state.step + 1
   }));
Clarity
  • 10,730
  • 2
  • 25
  • 35