0

i want to add data after uploading 1 image

const [file, setFile] = useState(null);

const handleUpload = (e) => {
    setFile(e.target.files);
};

<input
  type="file"
  onChange={(e) => handleUpload(e)}
  ref={fileInputRef}
  multiple
/>

this was work if i select 2 or more files at once. however i want to handle after choosing 1 image. user will be upload using the same input.

i have tried using method below and created error TypeError: file is not iterable

const handleUpload = (e) => {
    setFile([...files, e.target.files]);
};

or

const handleUpload = (e) => {
    let filesArray = file;
    if (file) {
      for (var i = 0; i < file.length; i++) {
        filesArray.push(e.target.files[i]);
      }
    }
    setFile(filesArray);
};

do you guys have any solution?

1 Answer 1

1

You should first set the default value for file as an array in your useState, then while using the set method you need to use the spread (...) operator properly. This will resolve your error TypeError: file is not iterable

Below are the changes that you will need to perform.

export default function InputComponent() {
  const [file, setFile] = React.useState([]);

  const handleUpload = (e) => {
    setFile([...file, ...e.target.files]);
  };
  return (
    <div>
      <input type="file" onChange={(e) => handleUpload(e)} multiple /><br/><br/>
      <textarea value={file}/>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your response. i already tried that but still giving the TypeError: file is not iterable because the file type.
I have made changes in handleUpload as wel, just check that function
thank you so much! sorry for my reply before. i forgot that i put setFile(null) in my useEffect. so it didn't work at first. thank you for your help

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.