0

I am using a state that at the start contains nothing. I want to update it with multiple input values. But when I try to do so my input value are just overwritting each other. For instance, let's say I set my input to test first then my object will be value : msg1 : 'test' but if I go in the second input and I type "test2" my object value will then be msg2 : 'test2' not the both together and that's what I want.

{
{name1:name1, value1: value1},
{name2:name2,  value2:value2} 
} 
/* OR something like this */
{
value1: value1,
value2: value2
}

I want it to be value1:'test' value2:'test2


const [msgCount, setMsgCount] = useState({});
const handleChange = name => value => {
        setTicketCount({name,value});
    }
<input type='number' onChange={handleChange('msg'+1)} />
<input type='number' onChange={handleChange('msg'+2)} />

Louisnot
  • 25
  • 7

2 Answers2

0

The setter of useState does not merge state like this.setState in class component, therefore you should use the functional update API:

// name === 'msg1', value = user text
const handleChange = name => value => {
  setTicketCount(prevState => ({...prevState, [name]: value});
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

you need to map an array to create a component for each input and put the states inside the component so it will duplicate the states along with the inputs https://stackoverflow.com/a/71973070/14548500

codmitu
  • 636
  • 7
  • 9