malexanders
malexanders

Reputation: 3343

React.js, why is setState changing all state values?

Why is setState() changing all state values? I have 4 inputs. The first two inputs are using the input autocomplete feature from google maps api.

when I enter text into the first input - the auto complete feature works fine. WhenI enter text into the second input, the first input is over written.

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

If you need more detailed context please don't hesitate to ask or clone this repo:

https://github.com/malexanders/roadtrip_react

Upvotes: 0

Views: 454

Answers (2)

John Ruddell
John Ruddell

Reputation: 25842

to answer your question you should change a few things.

first of all you dont need a new object to do this. secondly you should change the way you are calling this

<Input id="from" className={style.mapFormInput} type='text' label='Origin' hint="Enter a Location" placeholder='' name='from' value={this.state.from} onChange={this.handleChange.bind(this, 'from')} icon="add_location" />

on this line you are already specifying a name on the input. so just use that on your set state.

handleChange = (event) => {
  this.state[event.target.name] = event.target.value
  this.setState(this.state)
}

// change your render on the input to be this

<Input id="from" className={style.mapFormInput} type='text' label='Origin' hint="Enter a Location" placeholder='' name='from' value={this.state.from} onChange={this.handleChange} icon="add_location" />

Upvotes: 0

wintvelt
wintvelt

Reputation: 14101

Try

handleChange(name,value) {
  let newState = {}
  newState[name] = value
  this.setState(newState)
}

Upvotes: 1

Related Questions