I load a contact from a parent component which is sent to EditMainContact, which is a dialog/modal form where values are set inside inputs to edit them. So I use contacto as trigger of a useEffect so when it loads or changes, the relative data is converted into 2 arrays that I will use later. These are tels_empresa and emails_empresa.
At the same time, when these change, the values for the form are populated (this is where it doesn't work). It shows one input with the very last value. I am probably missing something here, maybe this is rerendering for some reason and at the end it returns a empty-ish array. The code is way longer than this but I put here the data I find necessary for the issue.
export default function EditMainContact({contacto}) {
const [tels_empresa,setTels_empresa] =useState();
const [emails_empresa,setEmails_empresa] =useState();
const [telFormValues, setTelFormValues] = useState([]);
const [emailFormValues, setEmailFormValues] = useState([]);
useEffect(()=>{
setTels_empresa(contacto?.telefonos_empresa?.split(",").map(par=>par.split(":")));
setEmails_empresa(contacto?.emails_empresa?.split(",").map(par=>par.split(":")));
},[contacto]);
useEffect(()=>{
tels_empresa?.map((inp, index)=>{
setTelFormValues([...telFormValues,{tel_identificador: inp[0], tel: inp[1]}]);
setFormValues({...formValues, ["telefonos_empresa"]: telFormValues});
});
},[tels_empresa]);
useEffect(()=>{
emails_empresa?.map((inp, index)=>{
setEmailFormValues([...emailFormValues,{email_identificador: inp[0],email:inp[1]}]);
setFormValues({...formValues, ["emails_empresa"]: emailFormValues});
});
},[emails_empresa])
}
[JSON.stringify(tels_empresa)]and[JSON.stringify(emails_empresa)]?setTelFormValues((prevTelFormValues) => [...prevTelFormValues, {tel_identificador: inp[0]...cause in the useEffect scope you may not have the up to date value oftelFormValues. (apply same thing to the other setters)prevTelFormValuesworked! I dont understand why since In my code I was using ...telFormValues which represents the current array data. I don't see why this makes a difference, but it does! Please Add it is answer so I can check it as solution. Thank you very much!