I'm working on a form view with a lot of fields being displayed dynamically given some other parameters. I have this very long form divided in different components.
In this part of the form, the user can define as many tasks as needed, and for each task there are some fields and buttons displayed, which are all managed on an object array inside the component's state (each task is an object included in the array).
I'm showing this by mapping the tasks array inside the render and everything is working fine, except for one thing, which are some toggle buttons. This is the code for each toggle button:
<Toggle label='¿Requiere registro?' data-key={e.numero} inlineLabel onText=' ' offText=' ' checked={e.regBool} onChange={this.checkRegistro} />
And this is the code of the function that is called:
public checkRegistro = (ev, checked: boolean) => {
const temp = checked;
ev.target.dataset ? console.log(ev.target.dataset.key) : console.log('no toma key');
const numero = ev.target.dataset ? ev.target.dataset.key : '1';
var arr = [...this.state.tareas];
const index = arr.map((e) => {return e.numero;}).indexOf(parseInt(numero));
if(index !== -1){
arr[index].regBool = temp;
this.setState({tareas: [...arr]})
console.log(arr[index].regBool);
}
}
As you can see, I specified data-key so I could access to the correct task (this.state.tareas) given the number of the task (tareas[index].numero).
The problem here is, sometimes (just sometimes) ev.target.dataset.key returns undefined. I try pressing the same toggle a couple of times, but only after I stop pressing it and wait a second it returns the correct value again
I suppose it's because as there is much to render, it doesn't get to specify the correct value on the data-key all the time, but I have no idea on how to make it work consistently. I've thought on separating it on another component being called for each task, but I'm not quite sure how that could help.
Any idea is well received, if you need more information you could also let me know. Please consider this is my first post here.
Thank you!!