Array concat make an object on every input

Viewed 51

I am trying to take input from user and push that input into array of object . It working fine but I face one problem . When I type for exmaple ( Nine ) so it created 4 object inside array . I want only single object and store user value. It created an array like

[
 {name : 'text', value : 'N'}
 {name : 'text', value : 'Ni'}
 {name : 'text', value : 'Nin'}
 {name : 'text', value : 'Nine'}
]

Could someone please help me how to resolve this issue. Thanks

Code

 <input
    type="text"
    className="inputStyle"
    placeholder={item.fieldName}
    onChange={(e) =>
    this.generateExtraFieldData(
     e.target.value,
     item.fieldName
    )
   }
/>

generateExtraFieldData = (data, type) => {
    const { optionalFields } = this.state;
    var joined = optionalFields.concat({ name: "text", value: data });

    this.setState({
      optionalFields: joined,
    });
  };
3 Answers

You don't need to join or concat the fields yourself, you can simply use:

this.setState({
  optionalFields: {name:'text', value: data},
});

Ideally, you can consider that when the user stop typing, he won't insert a new character, so basically you can store only the most recent value and replace it every time:

 <input
    type="text"
    className="inputStyle"
    placeholder={item.fieldName}
    onChange={(e) =>
      this.generateExtraFieldData(
       e.target.value,
       item.fieldName
     )}
/>

generateExtraFieldData = (data, type) => {
    this.setState({
      optionalFields: { name: "text", value: data },
    });
  };

I believe you should listen to onBlur event but rather waiting for the user to stop typing. That's because if a user types nin and then stops, he would try again to fix the typo by appending e to nin which will result again in two different objects with the following

[ { name: "text", value: 'nin' }]
[ { name: "text", value: 'nine' }]

While if you listen to onBlur event, you can just empty the input and ask user to add a new optional field. That way giving the user time to think and look in case of any typo

  <input
   type="text"
    className="inputStyle"
    placeholder="test"
    onBlur={(e) =>
          this.generateExtraFieldData(
          e.target, // pass the e.target so we can empty the input after adding to array
          'name'
          )
        }
      />

generateExtraFieldData = (target, type) => {
  const { optionalFields } = this.state;
  var joined = optionalFields.concat({ name: "text", value: target.value });
  this.setState({
    optionalFields: joined,
  });
  target.value = '';
};

Here's the working Plunker

Related