1

I have this in constructor

this.state = {
  inputs : {}
}

This in handleInputChange (triggered on blur of input)

handleInputChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;

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

So that my state will look like

inputs : { name1 : "text1", "name2": "text2" }

I am getting this syntax error

 Unexpected token, expected , (20:12)

this.setState({
> 20 |       inputs[name]: value
     |             ^
  21 |     });

What is the correct syntax for this?

4 Answers 4

3
handleInputChange(event) {
  const target = event.target;
  const value = target.value;
  const name = target.name;
  let updatedInputs = this.state.inputs;
  updatedInputs[name]= value;
  this.setState({
    inputs: updatedInputs
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

this worked, we just need to declare updateInputs, else its throwing error. +1
2

Instead of passing an Object literal, pass a reference to an object instead.

With this you can add a computed (or semi-computed) property to the Object before passing it.

handleInputChange(event) {
  const target = event.target;
  const value = target.value;
  const name = target.name;
  let state = {inputs: this.state.inputs};
  state.inputs[name] = value

  this.setState(state);
}

1 Comment

this.state already has a object inputs. I want all the new key:value pairs inside that. like inputs : { name1 : "text1", "name2": "text2" }
1

While the above will work, it's better to manage state in a bunch of 'smaller' properties than in one big object. The reason is everything that depends on the top level state property (i.e. inputs) updates every time it changes. If you make each input it's own property directly in state, you'll have less to update, and it should be faster.(It might not be noticeable for this case.)

handleInputChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    this.setState({name: value});
}

1 Comment

Thats a good, but in this case I have few other info in state and for saving form data I just need to serialize inputs and send it via post
0

I believe the is problem is the inputs variable is not initiated.

this should work

handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
let inputs = {}
this.setState({
  inputs[name]: value
});

}

1 Comment

inputs is initialized, please see my constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.