Aims.kar
Aims.kar

Reputation: 151

How to dynamically fill a state based on textfield input?

I have a form that is rendered using a JavaScript object called model and a text-field that takes in an input. Based on this the state needs to be updated.

Unfortunately the state is updated to the last entry input. And not all the values in the form that have been filled in.

I haven't managed to get the methods mentioned here to work for me: How to fill a specific state with a dynamic key?

constructor(props) {
    super(props); 
    this.state = {
       Form:{},
    }
}

 onChange = (e, key, type) => {

    let list = [];

    if (type === "text") {
      list[key] =  e.target.value;
    } 

    else {
      // LOGIC TO HANDLE NON TEXT VALUES
      let found = this.state.Form[key]? true : false;
      if (found) {  
        list[key] = false;
        } else {
          list[key]= true;
        }
    }

    this.setState({ Form: list });

  };

renderform = () => {
  return model.map(m => {

     <TextField
          type={m.type}
          key={m.key}
          onChange={event => { this.onChange(event, m.key, "text"); }}
        />

  })
}



Upvotes: 0

Views: 173

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10652

Try this:

this.setState(prevState => ({ Form: {...prevState.Form, ...list} }));

because when you use this.setState({ Form: list }); your Form state is overwritten with a new array everytime.

Upvotes: 1

Related Questions