When uploading the same image, onChange Event is not getting fired in Reactjs

Viewed 38

First issue:

let eventNameArray = [
  {
    label: "Birthday",
    files: [],
  },
  {
    label: "Wedding Day",
    files: [],
  },
  {
    label: "Joining Day",
    files: [],
  },
];
            
<Input  accept="image/*" type="file" onChange={(e) => handleImagesUpload(e)} />

If i try to upload same image again, onChange event is not firing. I have found a solution for this to fire up an event.

By setting the current value null, I was able to fire up the event. But still one more problem occurs. that will be 2nd issue

  const handleImageOnClick = (e)=>{
    e.target.value = null;
    e.target.files = null;
  }


<Input accept="image/*" type="file" onChange={(e) =>handleImagesUpload(e)}  onClick={(e)=> handleImageOnClick(e)} />

2nd Issue :

let eventNameArray = [
  {
    label: "Birthday",
    files: [],
  },
  {
    label: "Wedding Day",
    files: [],
  },
  {
    label: "Joining Day",
    files: [],
  },
];

Now i am uploading an image for "Birthday Event" which will be stored in the birthday object of eventNameArray.

So far , So good.

When I try to upload the same image for Wedding Day Event, the onChange event is firing.

But, As we are setting the e.target.value = null,
The image that we stored in the birthday event object, is getting vanished , the same image we upload for Wedding Day event, gets stored in the wedding day object.

This is the problem.

What i want: When i upload an image, it should store in the appropriate object of eventNameArray. Again , If i upload the same image for different event (event : birthday event, wedding day event) , In both the places, The same image should be there in the eventNameArray.

 const handleImagesUpload = (e) => {

    const files = e.target.files;
    
    if(eventName === 'Birthday' ){
      eventNameArray.forEach((el, i) => {
        if (eventName === el.label) {
          el.files =  files;
        }
      });
      toast.success('Image(s) are added!');
    }else  if(eventName === 'Wedding Day'){
      eventNameArray.forEach((el, i) => {
        if (eventName === el.label) {
          el.files = files;
        }
      });
      toast.success('Image(s) are added!');
    } else  if(eventName === 'Joining Day' ){
      eventNameArray.forEach((el, i) => {
        if (eventName === el.label) {
          el.files = files;
        }
      });
      toast.success('Image(s) are added!');
    }
  };

     const handleImageOnClick = (e)=>{
        e.target.value = null;
        e.target.files = null;
      }
    
    <Input accept="image/*" type="file" onChange={(e) =>handleImagesUpload(e)}  onClick={(e)=> handleImageOnClick(e)} />

Thanks in advance !!!!

0 Answers
Related