1

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: file.size,
      })
    );
    selectedFiles.length === 0 ? setselectedFiles(files) : setselectedFiles(oldFiles => [...oldFiles,...files])
  }

At this point how can we add only new file and remove duplicate file

setselectedFiles(oldFiles => [...oldFiles,...files])
7
  • does files includes oldFiles's elements, or just new elements only? Commented Aug 27, 2020 at 5:13
  • just new elements Commented Aug 27, 2020 at 5:15
  • you should also provide example of a file element Commented Aug 27, 2020 at 5:15
  • just new elements so why you worry about removing duplicated files? Commented Aug 27, 2020 at 5:16
  • In new element may be he select same files then it will add duplicate files Commented Aug 27, 2020 at 5:17

2 Answers 2

1

You could create a lookup object with key-value pairs of filePreview-file and grab values from that

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

  const dedupFiles = Object.values(
    [...selectedFiles, ...pendingFiles].reduce((lookup, file) => {
      if (lookup[file.name] === undefined) {
        lookup[file.name] = file
      }
      return lookup
    }, {})
  )

  setselectedFiles(dedupFiles)
}
Sign up to request clarification or add additional context in comments.

Comments

1

Maybe this is what you need?

function handleAcceptedFiles(files) {
  // Map over the current selection of files, generate required fields
  const newFiles = files.map(file => {
    return Object.assign(file, {
      preview: URL.createObjectURL(file),
      formattedSize: file.size,
    });
  });

  // Find non-duplicate entries in previously selected files
  const nonDupFiles = selectedFiles.filter(oldFile => {
    const index = newFiles.findIndex(newFile => newFile.preview === oldFile.preview);
    return index === -1;  // index -1 => file wasn't found => non duplicate
  });

  // Concat of new files and non-dup files is what we need in state
  setselectedFiles(newFiles.concat(nonDupFiles));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.