Reputation: 303
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.
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.
Upvotes: 0
Views: 705
Reputation: 403
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
Upvotes: 1
Reputation: 190
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.
Upvotes: 1