0

I am trying to make multiple files upload, and have preview. If the image is click it will be deleted from array.

I already can delete the file from the array, but the problem is the component didn't update after i delete the data.

Here are the CodeSandbox

Here is my Code :

import { useState } from "react";
import "./Upload.css";
const Upload = () => {
  const [file, setFile] = useState([]);
  console.log(file);

  const handleUpload = (e) => {
    setFile([...file, ...e.target.files]);
  };
  const deleteFile = (index) => {
    if (file !== []) {
      var newArr = file;
      newArr.splice(index, 1);
      console.log(newArr, "after");
      setFile(newArr);
    }
  };

  return (
    <div>
      <input type="file" onChange={(e) => handleUpload(e)} multiple />
      <br />
      <br />
      {file !== [] &&
        file.map((data, index) => (
          <div key={index}>
            <img
              src={URL.createObjectURL(data)}
              alt="file-img"
              className="image-preview"
              onClick={() => deleteFile(index)}
            />
          </div>
        ))}
    </div>
  );
};
export default Upload;

The image didn't removed after i click. but the files in array get deleted. Thank you before!

Gerry
  • 281
  • 1
  • 3
  • 14

2 Answers2

1

You delete item from state worng way. You need to return new Array instead of mutate state directly. You can use filter like this:

const deleteFile = (index) => {
  if (file !== []) {
    setFile((preFile) => preFile.filter((item, i) => i !== index));
  }
};
Viet
  • 12,133
  • 2
  • 15
  • 21
  • thank you, may i know why i need to filter array? and why i need to use function? as the answer in the top working too. – Gerry Aug 17 '21 at 05:17
  • Filter return new Array. And use the function or use state is the same in this case – Viet Aug 17 '21 at 05:28
  • You can read here to know more the different between use the function or use state: https://stackoverflow.com/questions/55510565/do-we-still-need-functional-setstate-way-in-react-hooks – Viet Aug 17 '21 at 05:29
0

You can filter out files array.

 const deleteFile = (index) => {
    if (file !== []) {
      setFile(file.filter((el, i) => i !== index));
    }
  };
Asif vora
  • 3,163
  • 3
  • 15
  • 31