How to set file object in state with React hooks?

瘦欲@ 提交于 2020-03-25 17:49:13

问题


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


回答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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/57608588/how-to-set-file-object-in-state-with-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!