简体   繁体   中英

Push Object to array in react useState hook

I am declaring react state as below

const [selectedFiles, setselectedFiles] = useState([]);

Using them in function as below

function handleAcceptedFiles(files) {
    files.map((file) =>
      Object.assign(file, {
        preview: URL.createObjectURL(file),
        formattedSize: formatBytes(file.size),
      })
    );
    setselectedFiles(files);
  }

I am trying to add as below but not working

selectedFiles.length === 0 ? setselectedFiles(files) : setselectedFiles(oldFiles => [...oldFiles,files])

but it did not help me.

You might have setselectedFiles with the same reference on the previous array, which lead to no changes, so clone it to a new array (I clone by spreading)

function handleAcceptedFiles(files) {
  files.map((file) =>
    Object.assign(file, {
      preview: URL.createObjectURL(file),
      formattedSize: formatBytes(file.size),
    })
  )
  setselectedFiles([...files])
}

You are doing setselectedFiles(oldFiles => [...oldFiles,files])

which will add the array as a new element to the existing array something like this

let array = [1,2,3];
let array2 = [4,5,6];

let output= [...array,array2]
console.log(output) // [1,2,3,[4,5,6]]

// change the output which concat 2 arrays using spread 
output= [...array,...array2];

console.log(output) // [1,2,3,4,5,6]

so for your solution replace

setselectedFiles(oldFiles => [...oldFiles,files])

by

setselectedFiles(oldFiles => [...oldFiles,...files])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM