Home > Mobile >  React returning empty array after populating it (possibly re-render problem)
React returning empty array after populating it (possibly re-render problem)

Time:05-13

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])

}

CodePudding user response:

The issue is that inside the useEffect callback's scope you don't have the up to date values of telFormValues, emailFormValues and formValues.

Every time tels_empresa or emails_empresa changes, the useEffect callback gets recreated and runs, but it points to an "old" value of the other consts you use inside the callback's scope.

To fix this you have 2 options:

  1. Add the other consts to the dependencies array. (but this will make the useEffect run also when the other consts change)

  2. Use the setter previous value functionality. This makes sure you are getting the up to date value. Here is an example: (and you need to do the same for the other setters)

    setTelFormValues((prevTelFormValues) => [...prevTelFormValues, {tel_identificador: inp[0]...

  • Related