Is it possible to use same function to setstate on different objects

Viewed 56

I am trying to figure out if it's possible to capture input/checkbox onchange events and update the state from the same function? The reason behind this is that I am still learning React and would like to learn how to save the state properly.

I've tried to save the state the following way, but I am probably making some mistakes:

constructor(props) {
    super(props);
    this.state = {
      list: [],
      test: {
        text: "placeholder",
        age: null
      },
      anotherTest: {
        name: "",
        info: ""
      }
    };

handleChange = e => {
    var target = e.target.name;
    var value = e.target.value;
    this.setState({
      ...this.state,
      [target]: value
    });
  };

And the render:

 <input name="text" value={this.state.test.text} onChange={e => this.handleChange(e)} />

 <input name="name" value={this.state.anotherTest.name} onChange={e => this.handleChange(e)} />

I am in this example creating a new state instead of updating the targeted object.

Whole test enviroment:

Edit creact-example-jvb6o

1 Answers

you're nearly there. just change it to this:

this.setState(prevState => ({
    anotherTest: {                  
        ...prevState.anotherTest,    
        [target]: 'something'       
    }
}))

if you want to reuse function do this:

handleChange = (e, stateValue) => 
   this.setState(prevState => ({
       [stateValue]: {                  
          ...prevState[stateValue],    
          [target]: 'something'       
       }
   }))

then call it like so:

e => this.handleChange(e, 'name')

or

e => this.handleChange(e, 'anotherTest')

Related