Melissa94
Melissa94

Reputation: 423

onChange on input doesn't update state using setState

I have state that store array, like ['X', 'XL'] but my code code won't work I have no clue why?

class App extends Component {
  state = {
    shirtsSize: ['X', 'XL']
  }
  handleChange = index => e => {
    const { shirtsSize } = this.state
    this.setState({
      [`${shirtsSize[index]}`]: e.target.value
    })
  }

  render() {
    const { shirtsSize } = this.state
    return (
      <div className="App">
        <label htmlFor="shirtsSize">Sizes</label>
        <button>+</button>

        {shirtsSize.map((lang, index) => (
          <input
            type="text"
            name="shirtsSize"
            id="shirtsSize"
            value={lang}
            onChange={this.handleChange(index)}
          />
        ))}
      </div>
    )
  }
}

Couldn't spot where is the mistake.

Upvotes: 0

Views: 207

Answers (2)

Sergii Vorobei
Sergii Vorobei

Reputation: 1497

Seems like you need smth like:

handleChange = index => e => {
  const {shirtsSize} = this.state
  shirtsSize[index] = e.target.value
  this.setState({shirtsSize: shirtsSize.slice()})
}

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 282080

With

this.setState({
  [`${shirtsSize[index]}`]: e.target.value
})

you aren't updating data in the shirtSize array, but createing a new key like shortsSize[0] and so on. You need to update the array like

const value = e.target.value;
this.setState(prevState => ({
  shirtsSize: [...prevState.shirtsSize.slice(0, index), value, ...prevState.shirtsSize.slice(index + 1) ]
}))

or simply

const shirtsSize = [...this.state.shirtsSize];
   shirtsSize[index] = e.target.value
   this.setState({
      shirtsSize
    })

Upvotes: 1

Related Questions