2

I want to add to state and file object which I'm getting from input type file, and my problem is that I cannot update state with this:

currentTarget.files[0]

I'm getting this error:

DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

const [data, changeData] = useState({
  name: '',
  surname: '',
  cv: '',
});

HandleChangeEvent for getting data

const handleChangeData = ({ currentTarget }, key) => {
    if (currentTarget.type === 'file') {
      const files = currentTarget.files[0];
      changeData((prevState) => {
        console.log(prevState);
        return { ...prevState, [key]: files };
      });
    } else {
      // Validate property
      const val = currentTarget.value;
      const errorMessage = validateProperty(currentTarget);
      if (errorMessage) errors[currentTarget.name] = errorMessage;
      else delete errors[currentTarget.name];

      changeData((prevState) => {
        return { ...prevState, [key]: val };
      });
    }
  };

I want to get property files from input field and send it to backend

Freestyle09
  • 4,894
  • 8
  • 52
  • 83

3 Answers3

1

It looks like you are trying to pass a 'value' prop to the file input.

<input type="file" value="???" />

In React (as well as in html/js) file inputs values can only be set by a user, and not programmatically (due to security reasons).

You should work with your file input as with an uncontrolled component

https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag


Solution: Set the state's value from the file input (if you really need it), but don't set the input's value from state. Just find another way to show that the file has already been chosen in UI.

chumakoff
  • 6,807
  • 2
  • 23
  • 45
1

@chumakoff answer provide a good solution, but it worth noting, this has nothing to do with react. It is how the browser works.

You added only part of your code, so I assume you are trying to create a hook for setting value and change handler, just like you'll do with the default <input type="text"/>.

However, <input type="file"/> work differently - only the user can set it's value (e.i. the file object and the file name) for security reasons. As the error suggest, the only thing you can set this value to is - an empty string.

See this question about Angular, which produce the same error.

yuval.bl
  • 4,890
  • 3
  • 17
  • 31
-5
changeData(
    { 
        ...data, 
        [key]: val 
    }
);

EDIT: cause of comment

As my grandpa say: "RTFM"

https://reactjs.org/docs/hooks-state.html

I don't want to copy paste the doc

antho39
  • 80
  • 5
  • 3
    A good answer should provide an explanation rather than a piece of code. try to explain what led you to write this code and how it would help face the issue. – yuval.bl Aug 22 '19 at 12:10