I’m trying to make item swap in 2 array. There are 2 lists in the ui and the user select the items in the first list, then it should get removed from the 1st list and moved to 2nd list, where there are shown the selected items. The problem I got is that when I try to move the elements from the 1st and 2nd list with the setValue it doesen’t change the value value. The function getIndexA works, I use it because I have an array of object and in the input as value I have a proprierty of the object (the key).
(If I print array before removing the object and after removing the object I see the array is correctly removing the object but when I setListaFile it doesen’t change ListaFile values (even if I uncheck and recheck the input I see that array2 is made of the element selected and undefined) so it seems to work, but in render I still se the list as same of start (even with an useState connected to listaFile with a console log it doesen’t show the console log of listaFile)
const [fileSelezionati,setFileSelezionati] = useState([]); const [listaFile,setListaFile] = useState([]); function handleCheck(e){ if(e.target.checked){ var array = listaFile; var item = listaFile[getIndexA(listaFile,e.target.value)]; array.splice(getIndexA(listaFile,e.target.value),1); setListaFile(array); var array2 = fileSelezionati; array2.push(item); console.log("array2:",array2); setFileSelezionati(array2); } }
This part is in the return()
<ul> { listaFile.map((file,index)=>{ return <div key={file.key}><input type="checkbox" value={file.key} onChange={(e)=>handleCheck(e)}/> {file.key}</div> }) } </ul> <label>File selezionati:</label> <ul> { fileSelezionati.map((file,index)=>{ return <div><input key={file.key} type="checkbox" value={file.key} checked={true}>{file.key}</input></div> }) } </ul>
Advertisement
Answer
you can do this
<ul> { listaFile.map((file,index)=>{ return <div key={file.key}><input type="checkbox" value={file.key} onChange={(e)=>handleCheck(file.key, e.target.checked)}/> {file.key}</div> }) } </ul> <label>File selezionati:</label> <ul> { fileSelezionati.map((file,index)=>{ return <div><input key={file.key} type="checkbox" value={file.key} checked={true}>{file.key}</input></div> }) } </ul>
const [fileSelezionati,setFileSelezionati] = useState([]); const [listaFile,setListaFile] = useState([]); function handleCheck(key, checked){ if(checked){ const item = listaFile.find(f => f.key === key) setListaFile(listaFile.filter(f => f.key !== key)); setFileSelezionati([...fileSelezionati, item]); } }