1

How do you handle multiple input fields when its being displayed dynamically and update the input field state based on index.

const [state, setState] = useState[{value1: '',  value2: ''}]

const handleValue1 = (index, value) => {
  setState(prevObj => ({
    ...prevObj[index],
    value1: value,
  }));
  console.log(state);
}

const handleValue2 = (index, value) => {
  setState(prevObj => ({
    ...prevObj[index],
    value2: value,
  }));
  console.log(state);
}

return (
  <FlatList
    data={DATA}
    renderItem={({item, index}) => (
      <TextInput
        onChangeText={e => handleValue1(index, e)}
        value={state.value1}
      />

      <TextInput
        onChangeText={e => handleValue2(index, e)}
        value={state.value2}
      />
   />
)

There could be multiple TextInput pair, depending on the DATA, how do I dynamically update the values where ultimately I'll have:

[0]: {
  value1: 'some value',
  value2: 'another value',  
},
[1]: {
  value1: 'some value from another update',
  value2: 'another value from another update again',  
}

The issue is that if I update 1 TextInput, all the TextInput field is being updated with the same number, and then the updated state erases the array, and just keeps 1 object pair.

1 Answer 1

1

Just figured it out...

const handleValue1 = (index, value) => {
  state[index] = {...state[index], ['value1']: value};
  /*setState(prevObj => ({
    ...prevObj[index],
    value1: value,
  }));*/
  console.log(state);
}

const handleValue2 = (index, value) => {
  state[index] = {...state[index], ['value1']: value};
  /*setState(prevObj => ({
    ...prevObj[index],
    value2: value,
  }));*/
  console.log(state);
}

For if anyone else who might be interested.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.