skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. use useRef for taking peroperty inputs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search