K
K
KononovD2019-04-29 22:56:32
JavaScript
KononovD, 2019-04-29 22:56:32

How to set state dynamically?

There is the following code:

getval = ( propName, value ) => {
    const { formInfo } = this.state;

    this.setState( {
      formInfo[propName]: value
    } )
  }

The idea is as follows: the method receives the name of the field and its value, and I set its value by this name, I don’t want to write switch-case conditions for each possible option.
state looks like this:
state = {
    formInfo: {
      name: '',
      tel: '',
      email: '',
      subject: '',
      text: ''
    }
  }

The fact that it is impossible to do this - I understood, but how then to bring the idea to life?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-29
@KononovD

setVal = (propName, value) => {
  this.setState(state => ({
    formInfo: {
      ...state.formInfo,
      [propName]: value,
    }
  }));
};

Also renamed getval to setVal. Since the get verb is used in functions returning a value, and set in setting a value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question