Ajith
Ajith

Reputation: 845

Update an object property in useState Hook,Property name should be get from a variable

  const [fee, setFee] = useState({newPatient:'',establishedPatient:''})

  const field1='newPatient'        
  const field2='establishedPatient'
      

I want to update the fee object properties. Property name should be taken from variables (field1,field 2)

   onChangeText={(val)=>setFee({...fee,newPatient:val})}. //Working
   onChangeText={(val)=>setFee({...fee,...fee[field1]=val})} //Here I'm using field 1 variable to get the property name and its not working

expected result Here i can see 2 more properties 0,1

Upvotes: 0

Views: 392

Answers (1)

Someone Special
Someone Special

Reputation: 13588

This is what you want

onChangeText={(val)=>setFee({...fee, [field1]: val })}

Upvotes: 2

Related Questions