Why does File(image) takes two times to register in my NextJS app using Next-UI Input component

170 Views Asked by At

I don't know why my Input component is taking twice to take an image as an input. Everything seems to be working fine except it requires me to select the image twice... The first one renders the "title" fine but the "e.target.files" array is empty. The second time it renders all the data is displayed correctly. Can someone guide me to the solution.

const handleInputChange = (
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value, type } = e.target;

    setGalleryData((prevData) => ({
      ...prevData,
      [name]:
        type === "file" ? (e.target as HTMLInputElement).files?.[0] : value,
    }));
  };

... other code

return(
... other code
<form onSubmit={handleAddGallery}>
          <div className='mt-4 mb-4'>
            <Input
              isRequired
              type='text'
              name='title'
              label='Enter Gallery Title'
              onChange={handleInputChange}
              required
            />
          </div>
          <div className='mt-4 mb-4'>
            <div className='mb-2'>Upload Gallery Image (Required)</div>
            <Input
              isRequired
              type='file'
              name='image'
              onChange={handleInputChange}
              accept='image/*'
            />
          </div>
          <Button type='submit'>Add Gallery</Button>
        </form>
)

I am expecting that the input box should get the file in the 1st time and should not require me to reselect a file for the 2nd time. I am using NextJs 14.0.2, Next-UI, Tailwind CSS, Typescript

2

There are 2 best solutions below

1
Damon Darvishi On

The problem might be related the asynchronous nature of handling file inputs in React, when you try to get value of e.target.files immediately. you can get this value before updating state.

I mean try this one:

if(type === "file") const file = (e.target as HTMLInputElement).files?.[0];

after that update your state.

1
mehdi rezaii On

Use useRef for taking property inputs.