0

I am trying to create a function that allows me to remove a file from an array of files using the index, onclick.

**input:** files to upload stored in the state using hooks

**output:** files to upload stored in the state minus the removed file

here is what I have so far I am wondering if I am on the right track or is there a better way to go about doing this.

// remove document from uploadFiles array
      const removeFile = index => {
        // take an array of files and select a file at a given index
        // remove a file at a selected index
        // reassign all the indexs
        const selectFile = index;
        setFilesToUpload(filesToUpload.filter(file => file.selectFile[index] !== selectFile));
      };

      return (
        <div className={uploadStyles.fileContainer} key={uuid()}>
          <div className={uploadStyles.fileTitle}>
            <p>Document {(index += 1)}</p>
            <SquareButton
              label={"remove file"}
              icon={"x-mark"}
              small={true}
              name={file.selectFile}
              onClick={() => removeFile(index)}
            />
          </div>
          <p className={uploadStyles.filePath}>{file.path}</p>
          <p className={uploadStyles.fileTS}>
            {file.type}
            {"   "}|{"   "}
            {formatBytes()}
          </p>
          <div className={uploadStyles.progressLine} />
        </div>
      );
    });
  };

2 Answers 2

1

I believe you could use splice.

Before:

setFilesToUpload(filesToUpload.filter(file => file.selectFile[index] !== selectFile));

After:

setFilesToUpload(filesToUpload.splice(index, 1)));

The second parameter represents the amount of elements to be deleted

Splice

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place

Sign up to request clarification or add additional context in comments.

2 Comments

Let me know how it goes :)
it works however if i try to remove 1 file from the array if there are more than one it removes every index down to that file as well
1

In the filter method the 2nd argument is index, make use of this to simplify.

const removeFile = (index) => {
  setFilesToUpload(filesToUpload.filter((_, i) => i !== index));
};

1 Comment

this solution works however how do i handle cases where this is only one item in the array that i need to filter out.

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.