0

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.

Milind
  • 1,855
  • 5
  • 30
  • 71

2 Answers2

0

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])
}
hgb123
  • 13,869
  • 3
  • 20
  • 38
0

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])
Anup
  • 589
  • 4
  • 8
  • yes... use ```[...new Set(YOUR_ARRAY)]``` or if you are dealing with array of objects use ```[...new Set(YOUR_ARRAY.map(JSON.stringify))].map(JSON.parse)``` ... this is not the best answer though you will get your unique values in the array. – Anup Aug 27 '20 at 04:09