0

I have a state hook defined as:

  const [formState, setFormState] = useState({
    officeHourStart: "",
    officeHourEnd: "",
    timezone: "",
    doctorQuotas: {}
  }); 

and it is initiated like:

const mapUserIdQuotas = {0: 12, 1: 15};

setFormState({
  officeHourStart: settings.officeHourStart,
  officeHourEnd: settings.officeHourEnd,
  timezone: settings.timezone,
  doctorQuotas: mapUserIdQuotas
})  

Now I want to update the doctorQuotas part of it. Specifically, I need to update the {0: 12, 1: 15} to {0: 12, 1: 20}


  const updateDoctorQuota = (event) => {
    const id = parseInt(event.target.id);
    const value = parseInt(event.target.value); 
    setFormState({...formState, doctorQuotas: { ...formState.doctorQuotas, id: value}});
  }

This does not work since the result formState would be:

{
  officeHourStart: ... ,
  officeHourEnd:  ... ,
  timezone: ... ,
  doctorQuotas: {0: 12, 1: 15, id: 20}
}

I tried:


  const updateDoctorQuota = (event) => {
    const id = parseInt(event.target.id);
    const value = parseInt(event.target.value); 
    setFormState({...formState, doctorQuotas: { ...formState.doctorQuotas, [id]: value}});
  }

Then it becomes:

{
  officeHourStart: ... ,
  officeHourEnd:  ... ,
  timezone: ... ,
  doctorQuotas: {0: 12, 1: 15, NaN: 20}
}

How can I use the integer value of variable id to update the corresponding key-value pair?

Kid_Learning_C
  • 2,605
  • 4
  • 39
  • 71
  • Did you try logging what is the ID each time updateDoctorQuota is called? Is it possible to share a run-snippet? – lokprakash Nov 03 '21 at 16:19
  • I suggest using a state object to store doctorQuotas values, then update this state object instead of updating the formState. It will be much easier to access and change key, values in that case – Pankaj Prajapati Nov 03 '21 at 16:22
  • 2
    something must be wrong with id because [id]: value should work. try to console.log(id) and see what's there. – Sylvain Nov 03 '21 at 16:32
  • The object should update fine, the problems is in `event.target.id` that is not valid, try not parsing as int and just pass `event.target.id` or simply make sure that `event.target` has an `id`. Check this post [parseInt() returns NaN](https://stackoverflow.com/questions/10184368/parseint-always-returns-nan) – Ricardo Sanchez Nov 03 '21 at 17:45

0 Answers0