0

I am in the middle of implementing delete functionality to an image uploader. My error message is Cannot read property 'id' of undefined. I don't think I am assigning an id correctly and my approach is wrong to the task at hand.

  • Tried passing the object into the function and using JavaScripts delete API to delete the specific file. Not best practice to mutate the state directly rather to copy the state, modify then paste the new state.
  • Tried using the name as the indentifier but does not work. I am recommended to delete by an id or key.
import * as React from "react"
import Dropzone, { DropFilesEventHandler } from "react-dropzone"
import FaIcon from "components/FaIcon"
import { PrimaryButton } from "components/Buttons"

interface ImageFile extends File {
  preview?: string
  id: any
}

class ImageUpload extends React.Component {
  state = {
    files: []
  }

  onDrop: DropFilesEventHandler = (files: ImageFile[]) => {
    files.map(file => Object.assign(file, {
      preview: URL.createObjectURL(file)
    }))
    this.setState({ files: [...this.state.files, ...files] })
  }

  deleteImage = (file: ImageFile, index: number) => {
    console.log(file, index)
    // this.setState({
    //   files: this.state.files.filter(file => file.name !== file),
    // });
  }

  render() {
    const files = this.state.files.map((file: ImageFile, index: number) => (
      console.log(file),
      (
        <div key={index}>
          <div>
            <img src={file.preview} />
            <div onClick={() => this.deleteImage(file, index)}>
              <FaIcon icon="plus" />
            </div>
          </div>
        </div>
      )
    ))

    return (
      <div>
        <div>
          <h2>Upload Images</h2>
        </div>
        <form>
          <div>
            {files}
            <Dropzone onDrop={this.onDrop} accept="image/*">
              <FaIcon icon="plus"/>
            </Dropzone>
          </div>
          <div>
            <label>Category</label>
            <div>
              <input
                type="text"
                placeholder={"please enter / select..."}
                value={this.state.categoryInput}
                onChange={(e) => this.categoryInputValue(e)}
              />
            </div>
            <PrimaryButton>Upload</PrimaryButton>
          </div>
        </form>
      </div >
    )
  }
}

export default ImageUpload

I expect the file to be removed from the array. Actual result is nothing happens and error message appears.

3
  • why are you not using setState for deleting the element? Commented Apr 29, 2019 at 11:19
  • You are not updating the state. Commented Apr 29, 2019 at 11:19
  • You should be filtering out the object that matches the id, and using setState on that filtered array. Commented Apr 29, 2019 at 11:19

2 Answers 2

1

You could remove the object with an index value

deleteImage = (file, index) => {

    const myNewFiles = [...this.state.files]; // copy of Original State
    myNewFiles.splice(index, 1);
    this.setState({
      files: myNewFiles
    });
  };

and i've also made a sandbox example

https://codesandbox.io/embed/0krqwkokw

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

1 Comment

thanks! This is the approach I was looking for. I actually had just added react-uid to go with the approach of assigning an id and deleting it by id although I started getting error messages of cannot read id of never. This is wonderful thanks for taking the time to reply!
1
deleteImage = (file_id) => {
  const { files } = this.state;
  this.setState({
    files: files.filter(file => file.id !== file_id),
  });
}

You should write this as you are passing file id into the deleteImage function.

2 Comments

My file does not have an id. Not sure how I am supposed to assign one.
Oh, you changed the question. Anyway you can use the index to remove.

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.